Cricket PSL
Cricket PSL

Reputation: 11

How to get Total Sum of one column after multipling with other column values

take a look at this Database screenshot

There are two different columns, i want to multiply column "Purchase" value with Column "Stock". and then want to Sum of all answers. As per example, first row answer is 6600 and second row answer is 4500, i want total after multiplication and sum.

Tried this code: but getting 0 as result.

$purchase_sum = Stock::All()->sum('purchase' * 'stock');

Using Laravel eloquent method.

Thanks in advance

Upvotes: 0

Views: 2218

Answers (1)

fubar
fubar

Reputation: 17388

You can either multiply and sum the values using an SQL query (documentation):

$total = DB::table('stock')->selectRaw('purchase * stock AS total')->sum('total');

Or you can use a reducer on your collection (documentation):

$total = Stock::all()->reduce(function ($total, $item) {
    return $total + ($item->purchase * $item->stock);
});

Upvotes: 2

Related Questions