如何获取 laravel 中 table 列中的值的总和

How to get the sum of values in a table column in laravel

我在 Laravel blade 文件中有以下 table,它呈现数据。

对于每一列,我想获取总值并在底部显示总计,这样我就不必手动添加每一行。

执行此操作的最佳方法是什么,因为我似乎碰壁了,找不到任何在线帮助。

假设您想要产品价格总和。 在您检索产品的控制器中,例如:

$products = Product::where('status', '=', 'active')->get();

您还可以使用以下方式获得总和:

$totalPrice = Product::where('status', '=', 'active')->sum('price');

并在您的 blade 模板中使用此变量。

将另一行添加到您的 blade 文件中,如下所示:

<tr>
  <td nowrap style="overflow: hidden;">{{$name}}</td>
    @foreach($months as $month)
      <td>{{'£'.array_reduce($products, function ($previous, $product) use ($month) {
          $value = $product['current']->has($month->format('m/Y')) ? intval($product['current'][$month->format('m/Y')]->sum('batch_total')) : 0;
          return $previous + $value;
      }, 0)}}</td>
    @endforeach
      <td>{{'£'.array_reduce($products, function ($previous, $product) {
          return $previous + intval($product['on_hold']['total']);
      }, 0);}}</td>
      <td>{{'£'.array_reduce($products, function ($previous, $product) {
          return $previous + intval($product['current']->flatten()->sum('batch_total') + $product['on_hold']['total']);
      }, 0);}}</td>
      <td>{{array_reduce($products, function ($previous, $product) {
          return $previous + intval($product['last_year']->flatten()->sum('batch_total'));
      }, 0);}}</td>
</tr>