2016-11-18 124 views
1

這個問題看起來很愚蠢,但它令我煩惱。laravel OrderBy和總和

---------------------------------------------------------------- 
| account_id | order_id | sales | profit | currency | date  | 
|---------------------------------------------------|----------- 
| 10  | 100 | 550 | 10 | USD  |2016-10-11| 
| 10  | 101 | 144 | 4  | NZD  |2016-10-12| 
| 9  | 102 | 429 | 44 | NZD  |2016-10-13| 
| 10  | 103 | 797 | 80 | NZD  |2016-10-14| 
---------------------------------------------------------------- 

我想通過貨幣

$account = App\Account::find(10); 

$collection = $account 
       ->orders()    # relation between order and account 
       ->completedLastMonth() # scope of dates, 
       ->groupBy('currency')  # group by currency 
       ->sum('profit')   # sum of profit 

總結的利潤,但$collection是94

所以,我想造成這樣的事情

$collection = [ 
    'USD' => 10,  # total profit of USD 10 for account 10 
    'NZD' => 84  # total profit of NZD 80 + 4 = 84 for account 10 
] 

我有邏輯關於賬戶和訂單和上個月範圍之間的關係,請幫我A ggregate SUM和GROUP BY

回答

1
$account = App\Account::find(10); 
$collection = $account 
       ->orders()    # relation between order and account 
       ->completedLastMonth() # scope of dates, 
       ->groupBy('currency')  # group by currency 
       ->selectRaw('sum(profit) as sum, currency') 
       ->lists('sum','currency'); 
+0

下載原因將不勝感激。 –

+0

我的問題不是關於'completedLastMonth()'或'orders()'。 [https://github.com/illuminate/database/blob/master/Eloquent/Builder.php#LC55](https://github.com/illuminate/database/blob/master/Eloquent/Builder.php#LC55)從查詢返回。這不是查詢。我需要'收集'而不是'字符串' –