如何在没有 looping/foreach 的情况下对结果 mysql 查询结果执行操作
How do i perform an operation on resulted mysql query result without looping/foreach
$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
以上只是一个简单的例子,我如何在 php 中没有 looping/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?
但是如果我希望对结果查询执行 'specific algorithm' 而不是求和呢?
我不确定语法,但请尝试使用
User::all()->sum('spend_amount');
或
User::all()->select(DB::raw("SUM(spend_amount)")->get();
Laravel 默认使用 eloquent 提供 sum()
。
$total_spent_amount = DB::table('users')->all()->sum('spent_amount`);
$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
以上只是一个简单的例子,我如何在 php 中没有 looping/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?
但是如果我希望对结果查询执行 'specific algorithm' 而不是求和呢?
我不确定语法,但请尝试使用
User::all()->sum('spend_amount');
或
User::all()->select(DB::raw("SUM(spend_amount)")->get();
Laravel 默认使用 eloquent 提供 sum()
。
$total_spent_amount = DB::table('users')->all()->sum('spent_amount`);