首页 文章

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

提问于
浏览
0
  • 我有三个与hasMany关系相关的模型: Course / Lesson / Article - A Course hasMany Lessons hasMany Articles .

  • 我的 articles 表中有 int 列,名为 pos (位置的缩写),我想通过它来订购文章 .

  • 我在 CoursesController 中使用了以下查询,但它没有按照 pos 属性对文章进行排序:

公共功能节目(课程$课程,课程$课程,文章$文章){$ 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

任何帮助,将不胜感激!

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其中lesson_id = 1和pos < 2顺序pos desc limit1660μs\ app \ Http \ Controllers \ Users \ ArticlesController.php:55 select * from articles其中lesson_id = 1和pos> 2 order by pos asc limit1520μs\ app \ Http \ Controllers \ Users \ ArticlesController.php:59从课程中选择其中courses.id = 2 limit1610μsview:: users.articles.show:7 select * from lessons where lessons.id = 1 limit1530μsview:: users.articles.show: 8从articles.lesson_id = 1且articles.lesson_id不为null的文章中选择

2 回答

  • 0

    当您在节目视图中再次调用 $lesson->articles 时,基本上您将进行新的数据库调用 . 要获取正确的值,请使用变量 $articles

    @foreach($articles as $article)
       {{ $article->title }}
    @endforeach
    
  • 0

    如果要在视图中继续使用 lesson 对象,请使用 sortBy

    @foreach($lesson->articles->sortBy('pos') as $article)
       {{ $article->title }}
    @endforeach
    

相关问题