有没有办法在 Eloquent 中用 SUM 写这个 HAVING 查询而不用原始?
Is there a way to write this HAVING query with SUM in Eloquent without raw?
select
*
from
`foundations`
inner join `foundation_sector` on
`foundation_sector`.`foundation_id` = `foundations`.`id`
inner join `sectors` on
`sectors`.`id` = `foundation_sector`.`sector_id`
GROUP BY
foundations.id
HAVING
SUM(sectors.title = 'x')
AND SUM(sectors.title = 'y')
我试过的是
$postQuery = Foundation::query()
->join('foundation_sector', 'foundation_sector.foundation_id', '=', 'foundations.id')
->join('sectors', 'sectors.id', '=', 'foundation_sector.sector_id')
->groupBy('foundations.id')
->having('sectors.title', 'sum', $sectors, 'and');
但这不起作用。
我还是用raw,但是也准备了语句:
$postQuery = Foundation::query()
->join('foundation_sector', 'foundation_sector.foundation_id', '=', 'foundations.id')
->join('sectors', 'sectors.id', '=', 'foundation_sector.sector_id')
->groupBy('foundations.id');
foreach ($sectors as $sector) {
$postQuery = $postQuery->havingRaw('SUM(sectors.title = ?)', [$sector]);
}
select
*
from
`foundations`
inner join `foundation_sector` on
`foundation_sector`.`foundation_id` = `foundations`.`id`
inner join `sectors` on
`sectors`.`id` = `foundation_sector`.`sector_id`
GROUP BY
foundations.id
HAVING
SUM(sectors.title = 'x')
AND SUM(sectors.title = 'y')
我试过的是
$postQuery = Foundation::query()
->join('foundation_sector', 'foundation_sector.foundation_id', '=', 'foundations.id')
->join('sectors', 'sectors.id', '=', 'foundation_sector.sector_id')
->groupBy('foundations.id')
->having('sectors.title', 'sum', $sectors, 'and');
但这不起作用。
我还是用raw,但是也准备了语句:
$postQuery = Foundation::query()
->join('foundation_sector', 'foundation_sector.foundation_id', '=', 'foundations.id')
->join('sectors', 'sectors.id', '=', 'foundation_sector.sector_id')
->groupBy('foundations.id');
foreach ($sectors as $sector) {
$postQuery = $postQuery->havingRaw('SUM(sectors.title = ?)', [$sector]);
}