【问题标题】:Laravel group by & sum queryLaravel group by & sum 查询
【发布时间】:2021-07-21 08:53:54
【问题描述】:

如果我的 Laravel 表中有以下数据:

id event venue attendees
1 Event one gallery 5
2 Event two big hall 11
3 Event three gallery 6
4 Event four big hall 24
5 Event five gallery 7

是否可以编写 Eloquent 查询来获取每个场地的活动数量和每个场地的参加者总和,如下表所示?

venue events attendees
big hall 2 35
gallery 3 18

提前致谢。

【问题讨论】:

    标签: sql laravel eloquent


    【解决方案1】:

    在 L8 中

    您可以使用withSum() 聚合函数:

    https://laravel.com/docs/8.x/eloquent-relationships#other-aggregate-functions

    Venue::withCount('events')->withSum('events', 'attendees')->get();
    

    L8 之前:

    Venue::withCount([
        'events',
        'events as events_sum_attendees' => function($query){
            return $query->select(                      
                DB::raw('SUM(attendees)');
        }
        ])->get();
    

    【讨论】:

    • 我想如果我有 2 个表/模型——“场地”和“活动”,你的例子会起作用吗?由于我只有一个表中的数据,我假设简单的 SELECT 查询就足够了吗? $result = DB::select('SELECT venue, COUNT(event), SUM(attendees) FROM table GROUP BY venue');
    猜你喜欢
    • 1970-01-01
    • 2020-05-16
    • 2023-03-21
    • 2021-02-26
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多