Laravel Eloquent:与 groupBy 求和

Posted

技术标签:

【中文标题】Laravel Eloquent:与 groupBy 求和【英文标题】:Laravel Eloquent: sum with 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() 时已经准备好结果。那么有人可以指导我吗?

【问题讨论】:

【参考方案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();

【讨论】:

以上是关于Laravel Eloquent:与 groupBy 求和的主要内容,如果未能解决你的问题,请参考以下文章

Laravel Eloquent 所有与关系

Laravel eloquent join 与三个表

如何使用 eloquent / etc 与 laravel 编写关系函数?

Laravel Eloquent:与 groupBy 求和

Laravel Eloquent 嵌套关系枢轴与约束

Laravel Eloquent - 附加与 SyncWithoutDetaching