【问题标题】:Laravel Group and Show Popular RelationLaravel 组和显示热门关系
【发布时间】:2020-05-21 13:50:21
【问题描述】:

如果我有一个 users 表,其中有一列 country 和用户 belongsToMany 类别,有没有办法可以按国家/地区对用户进行分组,显示每个类别中最受欢迎的类别国家?

例如:

用户

id | name  | country

1  | UserA | Canada
2  | UserB | USA
3  | UserC | Canada

类别

id | Name
1  | Housing
2  | Cooking

category_user

id  | category_id | user_id
1   | 1           | 1
2   | 2           | 2
3   | 1           | 3

从表格中可以看出,住房是加拿大最受欢迎的类别。我似乎无法用代码显示。

我尝试过雄辩的“with”功能,但它只显示某个(第一个?)用户的类别。

任何帮助将不胜感激!

编辑:

Ersoy 给了我一个绝妙的解决方案,但它带来了一个我在发布问题时没有考虑到的新问题。我有另一个表“付款”与haveMany 关系,我对每个用户的所有amount 列求和。对于当前的连接查询,它会复制每个 belongsToMany 关系的数量,从而导致错误的总和。

付款

id | amount | user_id
1  | 500    | 1
2  | 200    | 2
3  | 150    | 1
4  | 100    | 3

【问题讨论】:

    标签: mysql laravel


    【解决方案1】:
    return User::leftJoin('category_user as cu', 'users.id', '=', 'cu.user_id')
            ->join('categories as c', 'cu.category_id', '=', 'c.id')
            ->groupBy(['country', 'c.name'])
            ->get([
                'users.country',
                'c.name',
                DB::raw('count(*) as total')
            ])
            ->groupBy('country')
            ->values()
            ->map(function (Collection $elt) {
                return $elt->sortByDesc('total')->first();
            });
    

    它将以下列格式打印。

    [
      {
        "country": "Canada",
        "name": "Housing",
        "total": 2
      },
      {
        "country": "USA",
        "name": "Cooking",
        "total": 1
      }
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-12
      • 2020-08-08
      • 2014-02-21
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      • 1970-01-01
      • 2020-05-30
      相关资源
      最近更新 更多