如何解决如何从SQL数据库获取行值总和并在Laravel 7的Blade View中的foreach循环上显示
我有一个存款表,其中有多行显示。我的刀片文件上有一个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
但是我还有另一个刀片文件,在其中我想显示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>
但是这些似乎都不起作用,我只会遇到错误。顺便说一句,这是我这张桌子的Schema
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');
}
实现此目标的最佳方法是什么?非常感谢!
解决方法
您可以像这样在集合上使用sum方法:
$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
作为所有金额的总数
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。