I have two models: posts and likes. Posts and likes have one-to-many relationship (so, one post has many likes). Likes model has also an isActive
field which shows liking is active or passive.
I want to get (sort) top 5 posts which had received maximum "active" likes (only likes whose isActive
field is true
would be considered).
Which Laravel query could give me the result?
My question is sorting the post not only according to a field of a related model but also count of entries in the related table.
This is the query:
$posts = Post::selectRaw('posts.*, count(likings.id) as likes_count')
->leftJoin('likings', function ($join) {
$join->on('likings.post_id', '=', 'posts.id')
->where('likings.isActive', '=', 1);
})
->groupBy('posts.id')
->orderBy('likes_count', 'desc')
->take(5)
->get();
And this is the error:
SQLSTATE[42000]: Syntax error or access violation: 1055 'database.posts.user_id' isn't in GROUP BY
(SQL: select posts.*, count(likings.id) as likes_count from 'posts' left join 'likings' on 'likings'.'post_id' = 'posts'.'id' and 'likings'.'isActive' = 1 group by 'posts'.'id' order by 'likes_count' desc limit 5)