简体   繁体   中英

Get the sum of a field using laravel eloquent

I started using Laravel and i loved this framework, right now i started working on a small project and i would like to know how can i use SUM to get the total of variant that i have in a table called variants , i would like to sum stock field,

stock field exist in variants table;

how can i use sum With the eloquent

this is my code

$products = Product::with(['category', 'brand', 'supplier'])->orderBy('id', 'desc')->paginate(15);

my model variant function

public function variant(){
        return $this->hasMany('App\Variant', 'product_id','id');
    }

Do you need to have any filters/conditions on which you sum? If not it could be as easy as:

$sum = Variant::sum('stock');

How is the variants table related to the products table?

It is convenient to for calling has-many sum with accessor

Add accessor:

In product model:

protected $appends = ['stock_sum'];

public function getStockSumAttribute() {
    return $this->variants()->sum('stock');
}

So you can call it by product:

$products = Product::with(['category', 'brand', 'supplier'])->orderBy('id', 'desc')->paginate(15);
$products->first()->stock_sum;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM