【发布时间】:2016-02-09 01:33:18
【问题描述】:
我有两个模型:posts 和 likings,它们具有一对多的关系(因此,一个帖子有很多赞)。 Likings 模型还有一个isActive 字段,显示喜欢是主动的还是被动的。
我想获得(排序)获得最多“活跃”赞的前 5 个帖子(仅考虑 isActive 字段为 true 的赞)。
这是查询:
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
这是由这个 laravel 查询产生的:
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();
这是错误:
SQLSTATE[42000]: Syntax error or access violation: 1055
'database.posts.user_id' isn't in GROUP BY
这里,posts.user_id 也是posts 表的一个字段,显示帖子的所有者。
如何解决此错误?更改mysql配置似乎不合逻辑(可能删除ONLY_FULL_GROUP_BY模式),但查询的最小更改。
【问题讨论】:
-
按照标准,您必须列出
group clause中的每个选定字段或使用聚合函数之一。