如何在与其他列值相乘后获得一列的总和
How to get Total Sum of one column after multipling with other column values
take a look at this Database screenshot
有两个不同的列,我想将列 "Purchase" 的值与列 "Stock" 相乘。然后想要所有答案的总和。根据示例,第一行答案是 6600,第二行答案是 4500,我想要乘法和求和后的总和。
尝试过此代码:但结果为 0。
$purchase_sum = Stock::All()->sum('purchase' * 'stock');
使用Laraveleloquent方法。
提前致谢
您可以使用 SQL 查询 (documentation) 对值进行乘法和求和:
$total = DB::table('stock')->selectRaw('purchase * stock AS total')->sum('total');
或者你可以在你的集合上使用 reducer (documentation):
$total = Stock::all()->reduce(function ($total, $item) {
return $total + ($item->purchase * $item->stock);
});
take a look at this Database screenshot
有两个不同的列,我想将列 "Purchase" 的值与列 "Stock" 相乘。然后想要所有答案的总和。根据示例,第一行答案是 6600,第二行答案是 4500,我想要乘法和求和后的总和。
尝试过此代码:但结果为 0。
$purchase_sum = Stock::All()->sum('purchase' * 'stock');
使用Laraveleloquent方法。
提前致谢
您可以使用 SQL 查询 (documentation) 对值进行乘法和求和:
$total = DB::table('stock')->selectRaw('purchase * stock AS total')->sum('total');
或者你可以在你的集合上使用 reducer (documentation):
$total = Stock::all()->reduce(function ($total, $item) {
return $total + ($item->purchase * $item->stock);
});