2013-03-12 94 views
4

我想知道是否有可能在一个查询中使用流利的查询生成器获取多个字段的总和。总结在Laravel的多个字段

我目前有两个表格:活动和与会者。参加者属于事件并具有两个字段:total_raised和total_hours。我想要做的是选择所有事件和总金额/在该事件上花费的总小时数。现在,如果我只是使用SQL我会做一些事情来的效果:

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 

不过,我似乎无法找到一种方法,采取多种资金一次用流利的查询生成器。有没有办法做我想用流利做什么,或者我应该把它做成一个原始的SQL查询?在simones答案

... 

->get(
    array(
    'events.id', 
    DB::raw('SUM(attendees.total_raised)'), 
    DB::raw('SUM(attendees.total_hours)') 
) 
); 

回答

4

您可以使用sum()即:

$q = DB::table('events') 
     ->join('attendees', 'events.id', '=', 'attendees.event_id') 
     ->sum('total_raised') 
     ->sum('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'), 
    )); 
+0

那是我最初的想法,但是当我这样做,我得到第二和调用一个错误,指出“试图调用总和(同样的方式)在非成员对象上“。 – Jonathan 2013-03-12 18:37:35

+0

@Jonathan我已经更新了我的答案 – Simone 2013-03-12 18:47:20

+0

问题,我最终使用了这个解决方案,但是我不得不添加一个轻微的补遗,因为我的数据库前缀没有包含在你的答案中。谢谢您的帮助。 – Jonathan 2013-03-12 20:07:06

0

大厦:

0

我在做我的项目同样的事情,这里是我找到的解决方案。我使用的是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();