SQL Laravel Eloquent:与 groupBy 相加
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24887708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent: sum with groupBy
提问by user2067888
Need eloquent/fluent query to get sum with groupBy function.
需要雄辩/流畅的查询才能使用 groupBy 函数获得总和。
So far I have tried:
到目前为止,我已经尝试过:
$this->data['no_of_pages'] = Document::sum('no_of_pages')
->groupBy('users_editor_id');
Which ofcourse gives me call to member function groupBy() on non-object
because of the fact that sum() will already execute the query and have result ready by the time grouBy() is applied. So can anyone guide me?
这当然给了我,call to member function groupBy() on non-object
因为 sum() 已经执行查询并在应用 grouBy() 时准备好结果。所以有人可以指导我吗?
回答by Jarek Tkaczyk
Document::groupBy('users_editor_id')
->selectRaw('sum(no_of_pages) as sum, users_editor_id')
->pluck('sum','users_editor_id');
// originally lists(), which was deprecated in favour of pluck in 5.2
// and dropped completely in 5.3
// ->lists('sum','users_editor_id');
// returns array like this:
array(
users_editor_id => sum,
...
)
Or this way (which I wouldn't use, since it won't be actual ORM result):
或者这样(我不会使用,因为它不会是实际的 ORM 结果):
Document::groupBy('users_editor_id')
->selectRaw('*, sum(no_of_pages) as sum')
->get();
// returns collection of Document pseudo models with additional sum field
回答by Koko Monsef
Document::Where('some_condition',true)
->select([DB::raw("SUM(debit) as total_debit"), DB::raw("SUM(credit) as total_credit")])
->groupBy('id')
->get()