【问题标题】:Laravel Eloquent: sum with groupByLaravel Eloquent:与 groupBy 求和
【发布时间】:2014-09-13 07:01:59
【问题描述】:

需要 eloquent/fluent 查询才能使用 groupBy 函数获取总和。

到目前为止我已经尝试过:

    $this->data['no_of_pages'] = Document::sum('no_of_pages')
                                ->groupBy('users_editor_id');

这当然给了我call to member function groupBy() on non-object,因为 sum() 已经执行查询并且在应用 grouBy() 时已经准备好结果。那么有人可以指导我吗?

【问题讨论】:

    标签: sql eloquent


    【解决方案1】:
    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
    

    【讨论】:

    • 注意:->lists() 自 laravel 5.2 起已重命名为 ->pluck()
    • 嗨。这不适用于模型中的“getTotalAttribute”方法等计算属性。
    【解决方案2】:
    Document::Where('some_condition',true)
       ->select([DB::raw("SUM(debit) as total_debit"), DB::raw("SUM(credit) as total_credit")])
       ->groupBy('id')
       ->get()
    
    
    

    【讨论】:

      【解决方案3】:

      一点点重构和方便的答案是(来自@keroles Monsef)

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

      【讨论】:

        猜你喜欢
        • 2020-06-24
        • 1970-01-01
        • 2014-12-25
        • 1970-01-01
        • 2022-01-21
        • 2022-01-01
        • 1970-01-01
        • 2018-07-25
        • 2021-04-21
        相关资源
        最近更新 更多