Laravel Eloquent:与 groupBy 相加 [英] Laravel Eloquent: sum with groupBy

查看:18
本文介绍了Laravel Eloquent:与 groupBy 相加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要 eloquent/fluent 查询才能使用 groupBy 函数求和.

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');

这当然给了我调用非对象上的成员函数 groupBy() 因为 sum() 将已经执行查询并在应用 grouBy() 时准备好结果.那么有人可以指导我吗?

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?

推荐答案

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

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

这篇关于Laravel Eloquent:与 groupBy 相加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆