2017-05-31 18 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 

以上只是一個簡單的例子,我如何做一些算法的結果查詢沒有循環/ foreach在PHP?我如何執行一個操作結果mysql查詢結果沒有循環/ 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

你只想要花錢的總和? –

+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。所以,每次你認爲你需要使用你的函數或算法時,都可以這樣稱呼它。 –

相關問題