Laravel - 嵌套关系中的 orderBy
Laravel - orderBy in nested relations
我有一个 eloquent 查询是这样的:
Forum::with(['comments.user'])->find($id);
这 returns 一个嵌套结果 forum -> its comments -> user who commented
。
如何在 comments
table 上应用 orderBy()
?
您可以在调用 with()
时在数组中传递一个闭包,以将更多查询元素添加到预加载查询中:
Forum::with([
'comments' => function($q){
$q->orderBy('created_at', 'desc');
},
'comments.user'
])->find($id);
现在您必须指定 comments
和 comments.user
,但请放心,它不会 运行 比仅 comments.user
.
更多的查询
$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();
我有一个 eloquent 查询是这样的:
Forum::with(['comments.user'])->find($id);
这 returns 一个嵌套结果 forum -> its comments -> user who commented
。
如何在 comments
table 上应用 orderBy()
?
您可以在调用 with()
时在数组中传递一个闭包,以将更多查询元素添加到预加载查询中:
Forum::with([
'comments' => function($q){
$q->orderBy('created_at', 'desc');
},
'comments.user'
])->find($id);
现在您必须指定 comments
和 comments.user
,但请放心,它不会 运行 比仅 comments.user
.
$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();