Php Laravel中多个字段的求和
我想知道是否可以使用fluent查询生成器在一个查询中获取多个字段的总和 我目前有两个表:事件和与会者。与会者属于活动,有两个字段:已提出的总小时数和总小时数。我要做的是选择所有事件以及引发的总金额/在该事件上花费的总小时数。现在,如果我只是使用SQL,我会做一些事情来达到以下效果:Php Laravel中多个字段的求和,php,laravel,Php,Laravel,我想知道是否可以使用fluent查询生成器在一个查询中获取多个字段的总和 我目前有两个表:事件和与会者。与会者属于活动,有两个字段:已提出的总小时数和总小时数。我要做的是选择所有事件以及引发的总金额/在该事件上花费的总小时数。现在,如果我只是使用SQL,我会做一些事情来达到以下效果: SELECT Event.id, sum(Attendees.total_raised), sum(Attendees.total_hours) FROM Events JOIN Attendees ON Ev
SELECT Event.id, sum(Attendees.total_raised), sum(Attendees.total_hours)
FROM Events JOIN Attendees ON Events.id = Attendees.event_id
GROUP BY Event.id
然而,我似乎找不到一种使用fluent查询生成器同时获取多个和的方法。有什么方法可以使用fluent完成我想做的事情,还是应该将其作为原始SQL查询?您可以使用sum()
,即:
$q = DB::table('events')
->join('attendees', 'events.id', '=', 'attendees.event_id')
->sum('total_raised')
->sum('total_hours');
如果不起作用,您可以尝试:
...
->get(
array(
'events.id',
DB::raw('SUM(attendees.total_raised)'),
DB::raw('SUM(attendees.total_hours)')
)
);
基于西蒙斯的回答。您可以通过运行两个查询来实现这一点
$query = DB::table('events')->join('attendees', 'events.id', '=', 'attendees.event_id');
$raised = $query->sum( 'total_raised' );
$hours = $query->sum( 'total_hours' );
这要视情况而定。如果是在管理/CMS方面,我会倾向于这个解决方案。如果是在前端,则应该在单个查询中完成,这样会更快。根据内容的不同,可能会有显著差异,也可能不会有显著差异
$result = DB::table('events')->join('attendees', 'events.id', '=', 'attendees.event_id')
->get( array(
DB::raw( 'SUM(attendees.total_raised) AS raised' ),
DB::raw( 'SUM(attendees.total_hours) AS hours' ),
));
我在我的项目中也在做同样的事情,下面是我找到的解决方案。我使用的是Laravel 5.2雄辩,这里是雄辩的声明 这个声明,我在我的项目中使用,请根据您的需要进行更改
$result = self::select("*", DB::raw('SUM(auction_amount) as total_auction_amount') , DB::raw('SUM(commission_amount) as total_commission_amount'),
DB::raw('SUM(deposit_amount) as total_deposit_amount'))
->groupBy('cp_user_id')
->get()
->toArray();
与查询时使用的方法相同,如
$result = self::select("*", DB::raw('SUM(auction_amount) as total_auction_amount') , DB::raw('SUM(Attendees.total_raised) as total_raised'),
DB::raw('SUM(Attendees.total_hours) as total_hours'))
->with('Attendees')
->groupBy('id')
->get()
->toArray();
这是我最初的想法,但是当我这样做的时候,我在第二个sum调用中得到了一个错误,上面写着“试图在非成员对象上调用sum()”。明白了,我最终使用了这个解决方案,尽管我确实需要添加一个小的补遗,因为我在回答中没有包含DB前缀。谢谢你的帮助。不正确的答案不应该被标记和投票。不能使用多个聚合函数。就像你不能做“->get()->all()”或“->sum()->get()”一样。这些函数不返回查询对象。