Laravel 5.7 - “orderBy”没有排序结果

  1. I have three models related through hasMany relationship: Course/Lesson/Article - A Course hasMany Lessons which hasMany Articles.

  2. I have an int column in my articles table named pos (short for position) and I want to order the articles by it.

  3. 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 where slug = 'this-is-article-one' limit 1 13.27ms\vendor\laravel\framework\src\Illuminate\Routing\ImplicitRouteBinding.php:35

select * from articles where lesson_id = 1 and pos < 2 order by pos desc limit 1 660μs\app\Http\Controllers\Users\ArticlesController.php:55

select * from articles where lesson_id = 1 and pos > 2 order by pos asc limit 1 520μs \app\Http\Controllers\Users\ArticlesController.php:59

select * from courses where courses.id = 2 limit 1 610μs view::users.articles.show:7

select * from lessons where lessons.id = 1 limit 1 530μs view::users.articles.show:8

select * from articles where articles.lesson_id = 1 and articles.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