I have two models: posts
and likings
which have one-to-many relationship (so, one post has many likes). Likings 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).
This is the query:
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
which is resulted from this laravel query:
Post::selectRaw('posts.*, count(likes.id) as likes_count')
->leftJoin('likes', function ($join) {
$join->on('likes.post_id', '=', 'posts.id')
->where('likes.is_active', '=', 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
Here, posts.user_id
is also a field of posts
table and shows the owner of the post.
How can I resolve this error? It seems it isn't logical to change mysql config (probably deleting ONLY_FULL_GROUP_BY
mode), but minimum change in the query.
Each non-aggregated field should be grouped.
It is standard behavior, which in mysql, depends on ONLY_FULL_GROUP_BY mode.
This mode is default enabled in >= 5.7
.
select posts.id, post.user_id, 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, posts.user_id
order by likes_count desc
limit 5
Or, you can aggregate
it:
select posts.id, MIN(post.user_id), 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
Other way - change sql_mode
:
SET SESSION sql_mode = '';
Also, you can divide it to 2 query:
IN clause
)In 5.7 the sqlmode is set by default to:
ONLY_FULL_GROUP_BY,NO_AUTO_CREATE_USER,STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
To remove the clause ONLY_FULL_GROUP_BY you can do this:
SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With