Laravel - 在嵌套关系中订购

时间:2015-02-17 21:20:17

标签: laravel eloquent

我有一个如此雄辩的查询:

Forum::with(['comments.user'])->find($id);

这将返回嵌套结果forum -> its comments -> user who commented

如何在orderBy()表格上应用comments

2 个答案:

答案 0 :(得分:12)

您可以在调用with()时在数组中传递闭包,以便将更多查询元素添加到预先加载的查询中:

Forum::with([
    'comments' => function($q){
         $q->orderBy('created_at', 'desc');
     },
    'comments.user'
])->find($id);

现在您必须指定commentscomments.user,但不要担心它不会仅仅comments.user运行更多查询。

答案 1 :(得分:0)

$this->data['user_posts'] = User_posts::with(['likes', 'comments' => function($query) {
    $query->orderBy('created_at', 'DESC');
},
'comments.replies' => function ($query) { 
    $query->orderBy('created_at', 'DESC'); }
])->where('status', 1)->orderBy('created_at', 'DESC')->get();