2016-11-18 9 views
1

Diese Frage scheint so albern, aber es nervt mich.laravel OrderBy und summe

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

Ich möchte von Währung Gewinn Summe

$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 

aber die $collection ist 94.

Deshalb möchte ich so etwas wie dieses Ich habe Logik

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

führen der Beziehung zwischen Konto und Bestellungen und letzten Monat Umfang, bitte helfen Sie mir für A Aggregate SUM und GROUP BY

Antwort

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

Gründe für den Download wird geschätzt. –

+0

Meine Frage bezieht sich nicht auf 'completedLastMonth()' oder 'orders()'. [https://github.com/illuminate/database/blob/master/Eloquent/Builder.php#LC55](https://github.com/illuminate/database/blob/master/Eloquent/Builder.php#LC55) Rückgabe von der Abfrage. es ist keine Abfrage. Ich brauche 'collection' im Gegenzug nicht' string' –