@AleksCzech

Как избежать большого количества подзапросов используя много withSum?

Имею такой запрос, который работает нормально, но на каждое поле для суммирования создается отдельный подзапрос
Возможно ли методами eloquent получить множество сумм одним подзапросом?

return Shop::withSum('sales as sum', 'sum')
            ->withSum('sales as checks', 'checks')
            ->withSum('sales as products', 'products')
            ->withSum('sales as return_sum', 'return_sum')
            ->withSum('sales as return_checks', 'return_checks')
            ->withSum('sales as return_products', 'return_products')
            ->get();


Такой sql получаю:
select `shops`.*, (select sum(`sales`.`sales`) from `sales` where `shops`.`bx_id` = `sales`.`shop_bx_id` and `date` between ? and ?) as `sum`, (select sum(`sales`.`sales`) from `sales` where `shops`.`bx_id` = `sales`.`shop_bx_id` and `date` between ? and ?) as `checks`, (select sum(`sales`.`sales`) from `sales` where `shops`.`bx_id` = `sales`.`shop_bx_id` and `date` between ? and ?) as `products`, (select sum(`sales`.`sales`) from `sales` where `shops`.`bx_id` = `sales`.`shop_bx_id` and `date` between ? and ?) as `return_sum`, (select sum(`sales`.`sales`) from `sales` where `shops`.`bx_id` = `sales`.`shop_bx_id` and `date` between ? and ?) as `return_checks`, (select sum(`sales`.`sales`) from `sales` where `shops`.`bx_id` = `sales`.`shop_bx_id` and `date` between ? and ?) as `return_products` from `shops`
  • Вопрос задан
  • 65 просмотров
Решения вопроса 1
@NubasLol
Как-то так

$leftJoinQuery = Sale::query()
            ->addSelect('shop_bx_id')
            ->addSelect(DB::raw('sum(checks) as checks'))
            ->addSelect(DB::raw('sum(return_sum) as return_sum'));
            ->groupBy('shop_bx_id');

        Shop::query()
            ->leftJoinSub($leftJoinQuery, 'sales', 'sales.shop_bx_id', '=', 'shops.bx_id')
            ->get();
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы