I have three models related through hasMany relationship:
Course
/Lesson
/Article
- ACourse
hasManyLessons
which hasManyArticles
.I have an
int
column in myarticles
table namedpos
(short for position) and I want to order the articles by it.-
I am using the following query in my
CoursesController
, but it's not sorting the articles by thispos
attribute:public function show(Course $course, Lesson $lessons, Article $articles) { $articles = $lesson->articles()->orderBy('pos', 'asc')->get(); return view('users.courses.show', compact('course', 'lessons', 'articles')); }
I'm using a foreach loop in blade:
@foreach($lesson->articles as $article)
{{ $article->title }}
@endforeach
Any help would be appreciated!
Laravel debugbar shows the following result:
select * from
articles
whereslug
= 'this-is-article-one' limit 1 13.27ms\vendor\laravel\framework\src\Illuminate\Routing\ImplicitRouteBinding.php:35select * from
articles
wherelesson_id
= 1 andpos
< 2 order bypos
desc limit 1 660μs\app\Http\Controllers\Users\ArticlesController.php:55select * from
articles
wherelesson_id
= 1 andpos
> 2 order bypos
asc limit 1 520μs \app\Http\Controllers\Users\ArticlesController.php:59select * from
courses
wherecourses
.id
= 2 limit 1 610μs view::users.articles.show:7select * from
lessons
wherelessons
.id
= 1 limit 1 530μs view::users.articles.show:8select * from
articles
wherearticles
.lesson_id
= 1 andarticles
.lesson_id
is not null