Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent: sum with groupBy

Tags:

sql

eloquent

Need eloquent/fluent query to get sum with groupBy function.

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?

like image 242
user2067888 Avatar asked Jul 22 '14 12:07

user2067888


2 Answers

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):

Document::groupBy('users_editor_id')    ->selectRaw('*, sum(no_of_pages) as sum')    ->get();  // returns collection of Document pseudo models with additional sum field 
like image 137
Jarek Tkaczyk Avatar answered Sep 17 '22 13:09

Jarek Tkaczyk


Document::Where('some_condition',true)    ->select([DB::raw("SUM(debit) as total_debit"), DB::raw("SUM(credit) as total_credit")])    ->groupBy('id')    ->get()   
like image 26
keroles Monsef Avatar answered Sep 17 '22 13:09

keroles Monsef