Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - orderBy in nested relations

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?

like image 458
aBhijit Avatar asked Feb 17 '15 21:02

aBhijit


1 Answers

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.

like image 68
lukasgeiter Avatar answered Sep 22 '22 01:09

lukasgeiter