如何在laravel中使用sum()


how to use sum() in laravel

我有一个表total_count

id  studid  month   year     acls_id   total_p total_a 
1   30       08     2015        12        5      2      
2   35       08     2015        12        5      2      
3   52       08     2015        12        5      2      
4   53       08     2015        12        5      2  
5   54       08     2015        12        5      2  
6   55       08     2015        12        5      2  
7   30       09     2015        12        3      0  
8   35       09     2015        12        3      0  
9   52       09     2015        12        2      1  
10  53       09     2015        12        3      0  
11  54       09     2015        12        3      0  
12  55       09     2015        12        3      0 

我想计算每个学生的total_ptotal_a

eg: studid = 30, total_p = 5 and total_a = 2 .

所以我想要得到每个studid的每个月的总数,以及total_ptotal_a的总月份的总和。

我的控制器代码是
$total_counts = DB::table('total_count')
                       ->whereBetween('smonth',08, 09))
                       ->whereBetween('syear', 2015, 2015))   
                       ->sum('total_p);
                       ->sum('total_a);
视图blade.php

{{$total_counts->total_p}}
{{$total_counts->total_a}}

但它不工作…

如何在查询生成器格式中使用sum() ?

我想要这样的输出:

  studid     total_p   total_a
    30          8         2
    35          8         2
    52          7         3
    53          8         2
    54          8         2
    55          8         2

Eloquent的聚合函数sum()为所有匹配条件的行返回单个标量。如果您想获得一个行列表,您需要构建一个查询,根据学生的ID对他们进行分组,并计算他们每个人的总和。

这个查询应该能达到目的:

$total_counts = DB::table('total_count')
  ->whereBetween('smonth',08, 09))
  ->whereBetween('syear', 2015, 2015))
  ->groupBy('studid')
  ->get(['studid', DB::raw('SUM(total_a) AS sum_a'), DB::raw('SUM(total_p) AS sum_p')]);
在<<p>每一行strong>美元total_counts 将包含三个值: studid , sum_a sum_p