2017-05-31 13 views
1
$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でループ/ foreachせずに結果のクエリでアルゴリズムを実行するにはどうすればよいですか?ループ/ foreachなしで結果のmysqlクエリ結果に対して操作を実行するにはどうすればいいですか?

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

あなたは単にspend_amountの合計が必要ですか? –

+0

@GauravGuptaだけでなく、可能であれば、私はカスタムをしたい。 –

+0

私は石鹸のバーからLaravelを使いませんが、あなたのコレクションに 'reduce'ハンドラを適用したいのですか? https://laravel.com/docs/5.4/collections#method-reduce –

答えて

3

私は構文についてはよく分からないですが、雄弁使用して、デフォルトで

User::all()->sum('spend_amount'); 

または

User::all()->select(DB::raw("SUM(spend_amount)")->get(); 
+0

これはまさに正しいことです。 – Ohgodwhy

+0

私はlaravelがこれを行うことができることを知っています。上の質問にあるように、sumは単なる例です。私は和の代わりにカスタムアルゴリズムを実行したいのですか? –

+0

私の回答は正しいですか? – sensorario

4

Laravel提供sum()てみてください。

$total_spent_amount = DB::table('users')->all()->sum('spent_amount`); 
+0

私はlaravelがこれを行うことができることを知っています。上の質問で私が言っているように、sumは単なる例で、和の代わりにカスタムアルゴリズムを実行したいのですか? –

+0

Laravelでカスタムヘルパ関数を定義することができます。このhttps://stackoverflow.com/questions/28290332/best-practices-for-custom-helpers-on-laravel-5をご覧ください。だから、その関数やアルゴリズムを使用する必要があると思うたびに、それを呼び出します。 –

関連する問題