如何在没有循环/ foreach的情况下对生成的mysql查询结果执行操作

时间:2017-05-31 04:38:18

标签: php laravel php-7 php-5.6 laravel-eloquent

 $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?

但是,如果我想要特定算法'要对结果查询执行而不是求和?

2 个答案:

答案 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`);