I have an eloquent query like this:
Forum::with(['comments.user'])->find($id);
This returns a nested result forum -> its comments -> user who commented
.
How do I apply orderBy()
on comments
table?
You can pass a closure within the array when calling with()
to add further query elements to the eager loading query:
Forum::with([
'comments' => function($q){
$q->orderBy('created_at', 'desc');
},
'comments.user'
])->find($id);
Now you have to specify comments
and comments.user
but don't worry it won't run more queries than just 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();