我想根据每周添加的日期来计算。
如果可能,我想将这些查询合并到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;
答案 0 :(得分:3)
特别是学习SQL,group by
和aggregates
。
这是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');