43

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?

3 Answers 3

89
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
Sign up to request clarification or add additional context in comments.

2 Comments

Note: ->lists() has been renamed ->pluck() since laravel 5.2.
Hi. This doesn't work with calculated attributes like "getTotalAttribute" method in the Model.
10
Document::Where('some_condition',true)
   ->select([DB::raw("SUM(debit) as total_debit"), DB::raw("SUM(credit) as total_credit")])
   ->groupBy('id')
   ->get()


Comments

7

Little bit refactored and convenient answer is (from @keroles Monsef)

Document::Where('some_condition',true)
    ->selectRaw("SUM(debit) as total_debit")
    ->selectRaw("SUM(credit) as total_credit")
    ->groupBy('id')
    ->get();

4 Comments

How to sum total_debit and total_credit as say(total_amount) in same query?
It's Simple you think little bit: selectRaw("SUM(credit) + SUM(debit) as total_amount")
No in my case I want to sum total_debit and total_credit not the columns(credit and debit) I have count the user by status as total_active and total_inactive now i want to sum these total_active and total_inactive with selectRaw
Could you provide Sql-query info/example like:mycompiler.io/view/EWGZqc5CS61

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.