Sort eloquent query by model relationship
So I have the following query
$post = Post::where('id', $post_id)->with('ratings', 'ratings.user', 'ratings.like_votes')->firstOrFail();
How do I sort ratings by ratings with the most like_votes?
@jpeterson579 You could add a condition like below:
$post = Post::where('id', $post_id)->with(['ratings', 'ratings.user', 'ratings.like_votes' => function
($query) {
$query->orderBy('your_field', 'desc');
}])->firstOrFail();
Check Constraining Eager Loads
@meeshka Hmm, I think this would work but are you ordering the ratings.like_votes here?
To order the ratings by how many like_votes it has wouldn't it be something like
$post = Post::where('id', $post_id)->with(['ratings' => function ($query)
{
$query->orderBy($query.like_votes->count(), 'desc');
},
'ratings.user', 'ratings.like_votes'])->firstOrFail();
Please or to participate in this conversation.