需要eloquent / fluent查询才能与groupBy函数求和。
到目前为止,我已经尝试过:
$this->data['no_of_pages'] = Document::sum('no_of_pages')
->groupBy('users_editor_id');
由于sum()已经执行了查询并且在应用了grouBy()的时候已经准备好结果,因此哪个部分给了我call to member function groupBy() on non-object
。那么有人可以指导我吗?
答案 0 :(得分:34)
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,
...
)
或者这种方式(我不会使用它,因为它不会成为实际的ORM结果):
Document::groupBy('users_editor_id')
->selectRaw('*, sum(no_of_pages) as sum')
->get();
// returns collection of Document pseudo models with additional sum field
答案 1 :(得分:3)
Document::Where('some_condition',true)
->select([DB::raw("SUM(debit) as total_debit"), DB::raw("SUM(credit) as total_credit")])
->groupBy('id')
->get()
答案 2 :(得分:0)
一些重构和方便的答案是(来自@keroles Monsef)
Document::Where('some_condition',true)
->selectRaw("SUM(debit) as total_debit")
->selectRaw("SUM(credit) as total_credit")
->groupBy('id')
->get();