laravel按查询分组

93ze6v8z  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(322)

我在拉威尔有个问题:

return $this->hasMany(Facility::class)
            ->select("id", "port_id", "facility",
                DB::raw("(SELECT count('*') FROM port_facilities
                                    WHERE has_it = 1) as has_it_true"),
                DB::raw("(SELECT count('*') FROM port_facilities
                                    WHERE has_it = 0) as has_it_false"))
            ->groupBy('facility');

如果一个港口有某些设施,它就算数。我现在的问题是 groupBy 不起作用。一切都算数而不是 grouping 按设施。你知道我该怎么解决这个问题吗?

xqnpmsa8

xqnpmsa81#

你在混合两种拉维成分。一个是与elowent的关系定义,另一个是使用querybuilder。
从查询开始,您的“调整”查询应该是以下几行中的某个:

Facility::select("id", "port_id", "facility",
                DB::raw("(SELECT count('*') FROM port_facilities
                                    WHERE has_it = 1) as has_it_true"),
                DB::raw("(SELECT count('*') FROM port_facilities
                                    WHERE has_it = 0) as has_it_false"))
            ->groupBy('facility')->get();

如果您希望建立关系,那么在要指定关系的模型中,您应该执行文档中列出的操作:
https://laravel.com/docs/5.7/eloquent-relationships#defining-关系
建议:不要 count('*') 除非您真的需要(您可以计算一个或几个列并提高一些性能),否则不要将querybuilder与雄辩混合,除非您真的需要并且

8zzbczxx

8zzbczxx2#

您需要在此处使用条件聚合:

return $this->hasMany(Facility::class)
    ->select("facility",
        DB::raw("COUNT(CASE WHEN has_it = 1 THEN 1 END) AS has_it_true"),
        DB::raw("COUNT(CASE WHEN has_it = 0 THEN 1 END) AS has_it_false"))
    ->groupBy('facility');

这将对应于以下原始mysql查询:

SELECT
    facility,
    COUNT(CASE WHEN has_it = 1 THEN 1 END) AS has_it_true,
    COUNT(CASE WHEN has_it = 0 THEN 1 END) AS has_it_false
FROM port_facilities
GROUP BY
    facility;

请注意,我没有包括 id 以及 port_idSELECT 子句,因为mysql可能不接受这些列。一般来说,在做 GROUP BY facility ,我们只能选择 facility 以及除 facility .

相关问题