使用group by在Laravel Query Builder中聚合查询

时间:2015-01-08 12:54:26

标签: laravel

我有桌上的小鸟。

我想根据每周添加的日期来计算。

如果可能,我想将这些查询合并到Eloquent中的单个查询中。

 select count(id) as count1 from birds where dateadded= monday;

 select count(id) as count2 from birds where dateadded= tuesday;

 select count(id) as count2 from birds where dateadded= wednesday;

1 个答案:

答案 0 :(得分:3)

特别是学习SQL,group byaggregates

这是Laravel所需要的:

DB::table('birds')
  ->selectRaw('count(id) as count, kind')
  ->groupBy('kind')
  ->lists('count', 'kind');
  // or get()

lists将返回如下数组:

array(
  'kind_1' => '15',
  'kind_2' => '10',
  ...
);

get会返回一个stdObjects的数组,所以可能不是你想要的那样:

array(
  0 => StdObject {
    'kind' => 'kind_1',
    'count' => '15'
  },
  1 => StdObject {
    'kind' => 'kind_2',
    'count' => '10'
  },
  ...
);

如果您只想获得特定的kinds只鸟,请使用whereIn

DB::table('birds')
  ->selectRaw('count(id) as count, kind')
  ->groupBy('kind')
  ->whereIn('kind', ['kind_1', 'kind_2', 'kind_3'])
  ->lists('count', 'kind');