我有一个如此雄辩的查询:
Forum::with(['comments.user'])->find($id);
这将返回嵌套结果forum -> its comments -> user who commented
。
如何在orderBy()
表格上应用comments
?
答案 0 :(得分:12)
您可以在调用with()
时在数组中传递闭包,以便将更多查询元素添加到预先加载的查询中:
Forum::with([
'comments' => function($q){
$q->orderBy('created_at', 'desc');
},
'comments.user'
])->find($id);
现在您必须指定comments
和comments.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();