在一行laravel中得到()+ sum()

问题描述 投票:1回答:1

我的数据

invoice|amount|
0001   | 10000|
0001   | 10000|

现在我在Controller上的代码;

$invoices = Invoice::where('user_id', 1)
    ->where('status', 'Paid')
    ->orderBy('datePaid', 'desc')
    ->groupBy('no_invoice')
    ->get()
    ->sum('amount');  return view('invoice', ['invoices' => $invoices]);

我希望在我的foreach中使用get()和sum这样的字段数量显示所有数据。

invoice|total amount|
0001   | 20000|
php laravel get sum
1个回答
1
投票

您可以在select in query中使用selectRaw,然后像这样使用sum(amount)

$invoices = Invoice::selectRaw('*, sum(amount) as total')
    ->where('user_id', 1)
    ->where('status', 'Paid')
    ->orderBy('datePaid', 'desc')
    ->groupBy('no_invoice')
    ->get();

现在你可以打印了

foreach($invoices as $invoice){
     echo $invoice->total
}
© www.soinside.com 2019 - 2024. All rights reserved.