首页 > 解决方案 > 在 Laravel 中使用 Eloquent 创建 count() 和 groupBy

问题描述

我一直在尝试创建这个 SQL 命令:

SELECT d.id, v.vote, count(*) as cnt FROM draws d, votes v WHERE v.draw_id = d.id AND v.vote = "pos" GROUP BY d.id ORDER BY cnt desc

我做的:

                        $draws = DB::table('draws')
                                ->join('votes','draws.id', '=', 'votes.draw_id')
                                ->select(DB::raw('draws.id, votes.vote, count(*) as cnt'))
                                ->where('votes.vote', '=', 'pos')
                                ->groupBy('draws.id')
                                ->orderBy('cnt','DESC')
                                ->get();

我不知道失败在哪里,有人可以帮助我吗?

错误:

SQLSTATE [42000]:语法错误或访问冲突:1055 SELECT 列表的表达式 #2 不在 GROUP BY 子句中,并且包含在功能上不依赖于 GROUP BY 子句中的列的非聚合列“cendradraw.votes.vote”;这与 sql_mode=only_full_group_by 不兼容(SQL:select draws.id, votes.vote, count(*) as cnt from drawsinner join voteson draws. id= votes. draw_idwhere votes. vote= pos group by draws. idorder by cntdesc)

标签: phplaraveleloquent

解决方案


推荐阅读