Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

automica's avatar

Adding withSum and withAvg to nested query

I'm doing the following to get the number of orders attached to a purchaser:

 $collection = OrderEntity::with(['purchaser' => function($query){
                $query->withCount('orders');
            }])

what I'd like to do is also to return the sum of the orders.total and also the average of the orders.total

doing this:

$collection = OrderEntity::with(['purchaser' => function ($query) {
    $query
        ->withCount('orders')
        ->withSum('orders.total as order_sum`)
        ->withAvg('orders.total as order_average`)
 }])

blows up.

Can someone advise on correct approach for doing this?

0 likes
9 replies
MichalOravec's avatar
$collection = OrderEntity::with(['purchaser' => function ($query) {
    $query
        ->withCount('orders')
        ->withSum('orders as order_sum', 'total')
        ->withAvg('orders as order_average', 'total');
 }])->get();

The column has to be as a second parameter.

automica's avatar

actually looks like it would work if I was using laravel 8.

and I'm using Laravel 7 :P

I guess I would use withRaw in this instance?

automica's avatar

It's time to upgrade to Laravel 8 :)

not today it isn't :P

MichalOravec's avatar

I think you will spend less time with upgrading to Laravel 8 than trying to solve your problem in Laravel 7.

Please or to participate in this conversation.