mysql - 有没有办法在 Eloquent 中使用 SUM 编写这个 HAVING 查询而不需要原始数据?

标签 mysql laravel eloquent having

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');

但这不起作用。

最佳答案

我仍然使用原始,但也准备了声明:

  $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]);
        }

关于mysql - 有没有办法在 Eloquent 中使用 SUM 编写这个 HAVING 查询而不需要原始数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58236630/

相关文章:

mysql - 如何设计mvc实体模型

mysql - 使用 MySQL JSON 字段连接具有自定义字段的表

php - URI 中的 Laravel 条件

php - 如何修改已执行的 Laravel 查询生成器

php - 存储在表中,Laravel

sorting - 制定趋势查询 - Laravel Eloquent

mysql - 第 1 行不包含所有列的数据

mysql - Liquibase 抛出 "SQLException: connection is closed"

php - 如何在 laravel 的编辑 View 中更新图像?

laravel - 如何在laravel Eloquent 查询中获取前10个类别列表