2014-09-23 125 views
5

查詢生成器,我將如何使用查詢生成器在Laravel生成以下SQL語句:如何使用與SUM()列和GROUPBY

SELECT costType, sum(amountCost) AS amountCost 
FROM `itemcosts` 
WHERE itemid=2 
GROUP BY costType 

我已經試過幾件事情,但我不能讓sum()列與重命名一起使用。

我最新的代碼:

$query = \DB::table('itemcosts'); 
$query->select(array('itemcosts.costType')); 
$query->sum('itemcosts.amountCost'); 
$query->where('itemcosts.itemid', $id); 
$query->groupBy('itemcosts.costType'); 
return $query->get(); 

回答

10

使用groupBy和聚合函數(sum/count等)沒有任何意義。

查詢生成器的聚合總是返回單個結果。

這就是說,你要raw選擇這樣的:

return \DB::table('itemcosts') 
    ->selectRaw('costType, sum(amountCost) as sum') 
    ->where('itemid', $id) 
    ->groupBy('costType') 
    ->lists('sum', 'costType'); 

使用lists代替get是比較合適的位置,它會返回數組是這樣的:

[ 
'costType1' => 'sumForCostType1', 
'costType2' => 'sumForCostType2', 
... 
] 

隨着get你會:

[ 
stdObject => { 
    $costType => 'type1', 
    $sum => 'value1' 
}, 
... 
]