I have three models related through hasMany relationship: Course
/ Lesson
/ Article
- A Course
hasMany Lessons
which hasMany Articles
.
I have an int
column in my articles
table named pos
(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 this pos
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
When you call $lesson->articles
again in the show view, basically you make a new DB call. To get the correct values, use the variable $articles
:
@foreach($articles as $article)
{{ $article->title }}
@endforeach
If you want to continue using your lesson
object in your view, use sortBy
:
@foreach($lesson->articles->sortBy('pos') as $article)
{{ $article->title }}
@endforeach
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.