【问题标题】:how to use sum() in laravel如何在 laravel 中使用 sum()
【发布时间】:2015-08-19 11:46:15
【问题描述】:

我有一张桌子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 的总和。

我的控制器代码是

$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

【问题讨论】:

    标签: php mysql laravel laravel-4 eloquent


    【解决方案1】:

    Eloquent 的聚合函数 sum() 为匹配 criterai 的所有行返回单个标量。如果您想获取行列表,则需要构建一个查询,按学生 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

    【讨论】:

    • 例如:studid 30 total_p = 5 and total_a= 2 ,所以我编辑我的出席出席变成缺席。所以希望将 total_p 减 1,将 total_a 加 1。
    • 我正在使用此代码 DB::table($wys_total_attend_table)->whereIn('studid',[$student->id]) ->where('smonth',$date_exploded[1]) ->where('syear',$date_exploded[2]) ->where('stotal_a','!=',0) ->increment('stotal_a', 1,['studid' => $student->id ]) ->decrement('stotal_p', 1,['studid' => $student->id]);.但是不能正常工作...
    • 我正在检查您的其他问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2015-05-13
    • 2018-08-05
    • 2019-02-02
    • 2018-09-27
    • 2010-11-12
    相关资源
    最近更新 更多