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

osieman's avatar

Build Eloquent query with child aggregate

Hello All

Is it possible to build an eloquent query such that I get the parent, and then children as a sum aggregate. so,

Order:
1
2
3

OrderLines:
type 	value
A		10
A		12
B		10

Result :
$order[0]->orderlines[0]->type  would equate to A
$order[0]->orderlines[0]->value  would equate to 22

$order[0]->orderlines[1]->type  would equate to B
$order[0]->orderlines[1]->value  would equate to 10

Thanks

0 likes
9 replies
tykus's avatar

What is $order[0] and orderlines[0] in this scenario?

osieman's avatar

Sorry... the idea was if I do a dd($order[0]->orderlines[1]) that would be the result. I hope that makes sense.

tykus's avatar

It doesn't.

Anyway, there are many ways to achieve this; but first it depends on the nature of the relationship between Order and OrderLine models which is not clear above.

osieman's avatar

The relationship is a 1-n pk=id, fk=order_id

tykus's avatar

In that case, assuming you have an orderitems hasMany relation on the Order model, the following should work:

$orders => Order::with(['orderitems' => function ($builder) {
	$builder->selectRaw('sum(value) as value, type')->groupBy('type');
}])->get();

Now, you can use your preferred syntax:

$orders[0]->orderitems[0]->type;

$orders[0]->orderitems[0]->value;
osieman's avatar

Thanks for the code. Is there a way to do it without raw. In my case value in the child table is an accessor?

tykus's avatar

FFS. That is not the problem you described originally. Why would you omit an important piece of information such as the nature of the source data

osieman's avatar

I assumed eloquent query would mean that ?

osieman's avatar

Okay... I did it. not the most elegant way but it works.. I ended up creating an array of type and sum of values.

                    @php
                    $vats = array();
                    foreach($orderhdr->orderlis as $orderli){
                        $key = $orderli['ordervattype_id'];
                        if (!array_key_exists($key, $vats)) {
                            $vats[$key] = array(
                                'id' => $orderli['ordervattype_id'],
                                'vat' => $orderli['vat']
                            );
                        } else {
                            $vats[$key]['vat'] = $vats[$key]['vat'] + $orderli['vat'];
                        }
                    }
                    @endphp

Please or to participate in this conversation.