php - 如何在 Laravel 中使用 sum()

标签 php mysql laravel laravel-4 eloquent

我有一个表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

例如:studid = 30total_p = 5total_a = 2

因此,我想获取每个studid的每月总计以及总月份的total_ptotal_a总和.

我的 Controller 代码是

$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')]);

$total_counts 中的每一行将包含 3 个值:studidsum_asum_p

关于php - 如何在 Laravel 中使用 sum(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32094612/

相关文章:

php - 上传多个图像并将每个图像路径存储在mysql数据库的不同列中

php - Zend 框架 2 'quote_identifiers' => false

mysql - 特定日期的简单 mysql 连接

php - 搜索所有日期以及具有特定时间的两个日期之间的日期

php - 向 Laravel 队列中的 Sentry 发送错误报告

php - Laravel - 将模型中的时间转换为用户的时区

php - Laravel 5 将模型事件设置为模型删除时的 "clear up"数据透视表

php - 将xml数据导入mysql,如何管理对文件的修改

mysql - mysql中订单字段的默认值

php - 在不在模型中的 yii2 View 中添加自定义字段