如何从 SQL 数据库中获取行值的总和并在 Blade 中的 foreach 循环中显示 在 Laravel 7 中查看

How to get the Sum of Row Values from SQL Database and Display on foreach loop in Blade View in Laravel 7

我有一笔存款table,其中有多行显示。我的 blade 文件上有一个 foreach 循环,它工作得很好,并显示像图像

这样的值
@foreach ($moneytradeDeposits as $mtd)
   <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Deposited</div>
   <div class="h5 mb-0 font-weight-bold text-gray-800">Php {{$mtd->amount}}</div>
@endforeach

但我还有另一个 blade 文件,我想在其中显示 amount 行中的值的总和。我试过代码

<div class="h5 mb-0 font-weight-bold text-gray-800">Php {{$mtd->amount->sum}}</div>

<div class="h5 mb-0 font-weight-bold text-gray-800">Php {{$mtd->amount->sum()}}</div>

<div class="h5 mb-0 font-weight-bold text-gray-800">Php {{$mtd->amount->getTotal()}}</div>

<div class="h5 mb-0 font-weight-bold text-gray-800">Php {{$mtd->amount->total()}}</div>

但是其中 none 似乎有效,我只收到错误。顺便说一下,这是我的 Schema table

 Schema::create('money_trade_deposits', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('user_id');
        $table->string('mt_dep_number');
       
        $table->integer('amount');
        $table->string('payment_method');

        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

        $table->timestamps();


    });

我的控制器是

 public function store(Request $request)
{
    $request->validate([
        'amount' => ['required', 'integer', 'max:2000000'],
        'payment_method' => ['required', 'string', 'max:255'],

    ]);

    $moneyTradeDeposit = new MoneyTradeDeposit();

    $moneyTradeDeposit->mt_dep_number = uniqid('MTDepNumber-');

    $moneyTradeDeposit->amount = $request->input('amount');
    $moneyTradeDeposit->payment_method = $request->input('payment_method');

    $moneyTradeDeposit->user_id = auth()->id();

    $moneyTradeDeposit->save();


    return redirect()->route('mt.deposit')->withMessage('Added a New Deposit');
}

实现此目标的最佳方法是什么?非常感谢!

您可以像这样对集合使用求和方法:

$moneytradeDeposits->sum('amount')

或使用查询生成器方法:

MoneyTradeDeposit::sum('amount')

如果我真的明白你的问题,那么你可以这样做:

@php
   $sum = 0;
@endphp
@foreach ($moneytradeDeposits as $mtd)
   <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Deposited</div>
   <div class="h5 mb-0 font-weight-bold text-gray-800">Php {{$mtd->amount}}</div>
  @php
      $sum += (float)$mtd->amount;
  @endphp
@endforeach

现在您可以访问 $sum 总金额