时间:2018-09-19 21:33:01

标签: laravel eloquent

+---------+--------+---------+---------+
| date    | type_a | type_b  | type_zzz|
+---------+--------+---------+---------+
|01-01-18 | 12     | 10      |       1 |
|02-01-18 | 2      | 5       |       1 |
|03-01-18 | 7      | 2       |       2 |
|01-02-18 | 13     | 6       |      55 |
|02-02-18 | 22     | 33      |       5 |
+---------+--------+---------+---------+

嗨,

在上面的示例中,我想知道是否有可能在Laravel中获得结果时对月份进行分组并按月汇总(表是动态的,因此没有针对它们的模型,并且有些表没有列'type_a'其他没有'type_zzz'等。)

我希望从上表获得的东西是这样的:

"01" =>
    'type_a' : '21',
    'type_b' : '17',
    'type_zzz': '4'
 "02" => 
     'type_a' : '35',
     'type_b' : '39',
     'type_zzz': '60'

我正在使用以下代码按月对它进行分组,但是我无法找到按每一列返回总和的解决方案:

DB::table($id)->get()->groupBy(function($date) {
        return Carbon::parse($date->repdate)->format('m');;
  });

1 个答案:

答案 0 :(得分:2)

如果我正确理解了您的问题,则可以使用SQL查询对值进行分组和求和:

$grouped = DB::table('table_name')
    ->selectRaw('
        SUM(type_a) AS type_a,
        SUM(type_b) AS type_b,
        SUM(type_z) AS type_z
    ')
    ->groupByRaw('MONTH(date)')
    ->get();

或者,如果不想在每个查询中都指定列名,则可以在集合中使用groupByarray_columnarray_sum

$grouped = DB::table('table_name')
    ->get()
    ->groupBy(function ($item) {
        return Carbon::parse($item->date)->format('m');
    })
    ->map(function ($group) {
        $group = $group->toArray();
        $summed = [];

        $columns = array_keys($group[0]);
        array_shift($columns);

        foreach ($columns as $column) {
            $summed[$column] = array_sum(array_column($group, $column));
        }

        return $summed;
    });