dongyipa0028 2018-11-27 16:45
浏览 97

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

  • 写回答

2条回答 默认 最新

  • douwo8358 2018-11-27 17:17
    关注

    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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探