Laravel Eloquent: sum with groupBy

前端 未结 3 1002
名媛妹妹
名媛妹妹 2020-11-27 20:46

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\'         


        
相关标签:
3条回答
  • 2020-11-27 21:21
    Document::Where('some_condition',true)
       ->select([DB::raw("SUM(debit) as total_debit"), DB::raw("SUM(credit) as total_credit")])
       ->groupBy('id')
       ->get()
    
    
    
    0 讨论(0)
  • 2020-11-27 21:29

    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();
    
    0 讨论(0)
  • 2020-11-27 21:30
    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
    
    0 讨论(0)
提交回复
热议问题