You can give them aliases like this
Shop::withSum([ 'sales as sales_foobar_sum' => function
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
How can I get the sum for several columns with only one subquery?
Shop::withSum([
'sales' => function ($q) use ($dateFrom, $dateTo) {
$q->whereBetween('date', [
$dateFrom->format('Y-m-d'),
$dateTo->format('Y-m-d')
]);
}
], 'sum')
->withSum([
'sales' => function ($q) use ($dateFrom, $dateTo) {
$q->whereBetween('date', [
$dateFrom->format('Y-m-d'),
$dateTo->format('Y-m-d')
]);
}
], 'checks')
->toSql();
This code returns SQL like this:
select `shops`.*,
(select sum(`sales`.`sum`)
from `sales` where `shops`.`bx_id` = `sales`.`shop_bx_id`
and `date` between ? and ?) as `sales_sum_sum`,
(select sum(`sales`.`checks`)
from `sales` where `shops`.`bx_id` =`sales`.`shop_bx_id`
and `date` between ? and ?) as `sales_sum_checks` from `shops`
But I need SQl like this:
select `shops`.*,
(select sum(`sales`.`checks`) , sum(`sales`.`sum`)
from `sales` where `shops`.`bx_id` =`sales`.`shop_bx_id`
and `date` between ? and ?) as `sales_sum_checks` from `shops`
Please or to participate in this conversation.