I'm trying to order by a relationship field in the following way:
Post::with(['comments' => function($query) {
$query->orderBy('some_comment_field', 'desc');
}]);
But this doesn't work. How can I do this?
I use Laravel 5.8.
if you want to order by a comments fields, you should add it to the main select using join:
Post::with(['comments'])->join('comments','posts.id','comments.post_id')
->select(['posts.*','comments.some_comment_field'])
->orderby('comments.some_comment_field', 'desc')->get();
you can omit the eager loading comments and select the comments field you want, you can also use aliases to get clear columns names