$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?
しかし、「特定のアルゴリズム」を合計ではなく結果のクエリで実行したいのですか?
あなたは単にspend_amountの合計が必要ですか? –
@GauravGuptaだけでなく、可能であれば、私はカスタムをしたい。 –
私は石鹸のバーからLaravelを使いませんが、あなたのコレクションに 'reduce'ハンドラを適用したいのですか? https://laravel.com/docs/5.4/collections#method-reduce –