如何在sum()列和groupBy中使用查询生成器

use*_*435 8 php laravel-4

如何在Laravel中使用查询构建器生成以下SQL语句:

SELECT costType, sum(amountCost) AS amountCost
FROM `itemcosts`
WHERE itemid=2
GROUP BY costType
Run Code Online (Sandbox Code Playgroud)

我已经尝试了几件事,但是我无法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();
Run Code Online (Sandbox Code Playgroud)

Jar*_*zyk 18

使用groupBy和聚合函数(sum/ countetc)没有意义.

Query Builder的聚合始终返回单个结果.

也就是说,你想要raw选择这个:

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

在这里使用lists而不是get更合适,它会像这样返回数组:

[
 'costType1' => 'sumForCostType1',
 'costType2' => 'sumForCostType2',
 ...
]
Run Code Online (Sandbox Code Playgroud)

get你会有:

[
 stdObject => {
   $costType => 'type1',
   $sum => 'value1'
 },
 ...
]
Run Code Online (Sandbox Code Playgroud)