首页 > 解决方案 > 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

标签: laravellaravel-5eloquentlaravel-5.2

解决方案


您可以使用 SQL 查询(文档)将值相乘和求和:

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

或者您可以在您的收藏中使用减速器(文档):

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

推荐阅读