2014-09-23 173 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' 
}, 
... 
]