php - 如何在 Laravel 中汇总组集合?
问题描述
我在 Laravel 的数据库中有一组商品和价格的分组集合,我想在每个组之后对我的刀片模板中的总价格求和。因此,在每组之后显示总和。分组后无法求和。有不同的方法吗?请帮忙,谢谢
我的代码如下: 我的控制器
public function departmentSummary($id)
{
$items = \DB::table('invoices')
->where('user_id', $id)
->where('invoice_status', 1)
->whereDate('created_at', Carbon::today())
->get();
$grouped = $items->groupBy('invoice_category');
return view('inc.department-summary', [
'group' => $grouped->all()
]);
}
我的观点模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Department Report</title>
</head>
<body>
<style>
body{
font-size:15px;
margin: auto;
padding: 15px;
}
table, th, td {
border: 1px solid black;
}
</style>
<?php
$department = $group;
foreach ($department as $category => $group) {
echo "<h2>$category</h2>";
echo "<table>";
foreach ($group as $group) {
echo "<tr>";
echo "<td>";
echo "Name of Item";
echo "</td>";
echo "<td>";
echo "Qty";
echo "</td>";
echo "<td>";
echo "Amount";
echo "</td>";
echo "</tr>";
echo "<td>".$group->invoice_product_name ."</td>";
echo "<td>".$group->invoice_quantity."</td>";
echo "<td>".$group->invoice_total_price."</td>";
}
echo "</table>";
echo "Total:" . $group->sum('invoice_total_price') ;
}
?>
</body>
</html>
echo "Total:" . $group->sum('invoice_total_price') ;
无法总结,我该如何正确地做到这一点?
解决方案
推荐阅读
- html - 如何滚动到网页的特定部分?
- react-native - React Native Web:如何使文本居中?
- javascript - 使用下拉菜单和 javascript 更改特定文本框的值
- node.js - 即使在 kill -9 PID 之后也无法杀死节点进程
- python - Flask SQLAlchemy:(psycopg2.errors.AdminShutdown)由于管理员命令而终止连接
- python - NUMPY:如何使用嵌套的“for”循环填充二维数组
- node.js - 通过 Socket.IO 向所有关注者发送消息
- mysql - 如何在 Windows 10 上挂载 Docker MySQL 数据/套接字卷?
- c++ - 我对如何让我的天空盒与我的相机视图相匹配有点困惑
- arrays - 谷歌表格公式将列添加到数组?