I’m getting data from the posts table and there is a likes table that is related to this. I want to know how many likes each post has. I followed an example, but this way it gives an error.
I will leave the error after the code
$data = Post::query();
$data = $data->leftJoin('likes', 'posts.id', '=', 'likes.post_id');
$data = $data->selectRaw('posts.id, posts.status, COUNT(likes.id) AS curtidas')->groupBy('posts.id');
$data = $data->get();
Syntax error or access violation: 1055
2
Answers
You could also use Laravel’s Eloquent to achieve this; assuming there is a
likes
relationship between thePost
andLike
model, you could do this:Note that Laravel loads the number of likes in
likes_count
property on each post.To fix this issue, you can modify your query like this:
But you can achieve the same result with a simpler query by using Laravel’s Eloquent relationships and the withCount method.
Then, you can use the withCount method to retrieve the total likes for each post like this: