首页 > 解决方案 > 如何在 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') ;

无法总结,我该如何正确地做到这一点?

标签: phplaravel-8

解决方案


推荐阅读