Search code examples
mysqllaraveleloquenthaving

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

What I tried was

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

but that doesn't work.


Solution

  • I have still used raw, but prepared the statement also:

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