gpt4 book ai didi

sql - Laravel Eloquent : sum with groupBy

转载 作者:行者123 更新时间:2023-12-03 01:18:59 33 4
gpt4 key购买 nike

需要 Eloquent /流畅的查询才能使用 groupBy 函数获取总和。

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

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

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

最佳答案

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

关于sql - Laravel Eloquent : sum with groupBy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24887708/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com