9

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?

aBhijit
  • 5,261
  • 10
  • 36
  • 56

2 Answers2

22

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.

lukasgeiter
  • 147,337
  • 26
  • 332
  • 270
  • 1
    Any idea how to order the comments by a column in the user table in this example? – Vlad Apr 08 '19 at 06:11
  • @Vlad ```Forum::with([ 'comments', 'comments.user' => function($q){ $q->orderBy('your_user_column', 'desc'); } ])->find($id);``` – ggirodda Jul 23 '19 at 23:56
  • @ggirodda, I did expect this as solution but it does not order by the nested related table. Did you try this yourself? Does it work? – O Connor Nov 25 '19 at 13:51
  • I tried something just like that and it didn't work for me. Were you able to come up with a solution?? – cbloss793 Feb 06 '20 at 23:32
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();