$users = User:all();
//User:all() is based on the laravel eloquent model , it's just similar to 'select * from user' query
$total_spend_amount = 0;
foreach($users as $user)
{
$total_spend_amount += $user->spend_amount;
}
echo "Total spend amount :".$total_spend_amount;
//Note: In this simple example i just want to sum of all the spend_amount
上面只是一个简单的例子,如何在没有循环/ foreach的情况下对结果查询做一些算法?
User::all()->sum('spend_amount'); // this is the answer below and this is correct
//but how about if i want the 'specific algorithm' to be performed on the resulted query instead of sum?
但是,如果我想要特定算法'要对结果查询执行而不是求和?
答案 0 :(得分:3)
我不确定语法,但尝试使用
User::all()->sum('spend_amount');
或
User::all()->select(DB::raw("SUM(spend_amount)")->get();
答案 1 :(得分:1)
Laravel默认使用eloquent提供sum()
。
$total_spent_amount = DB::table('users')->all()->sum('spent_amount`);