Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent
Last updated 1 year ago.
0
// Product model
public function stockValueSum()
{
    return $this->hasMany('Stock')->sum('value');
}

then

Product::find($id)->stockValueSum();

will return sum of related 'value' columns on 'Stock' model's table

Mind though that you can't eager load this value with the above method. For doing this you would have to do some join

Last updated 1 year ago.
0
$product = Product::with(array('stock' => function($query) {
    $query->sum('value');
}))->where('id', '=', $id)->first();
Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

netm netm Joined 2 Apr 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.