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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With