【问题标题】:How to groupBy and count the pivot table in laravel?如何在 laravel 中分组和计算数据透视表?
【发布时间】:2019-10-22 06:21:58
【问题描述】:

我有三张桌子,

     User                   cities             user_cities

id  name    title           id   name        user_id   city_id
1    aaa   designer         1   cityA          2         1
2    bbb   developer        2   cityB          2         2
3    ccc   designer         3   cityC          1         2
                                               1         1
                                               2         3
                                               3         2

加入并查询数据库后,我的结果是,

data: {
   0: {
      id: 1
      name: aaa,
      title: designer,
      cities :[
         0: {
            id: 1,
            name: cityA
          }
          1: {
            id: 2,
            name: cityB
          }
          2: {
            id: 3,
            name: cityC
          }
        ]
    },
    1: {
      id: 2
      name: bbb,
      title: developer,
      cities :[
         0: {
            id: 1,
            name: cityA
          }
          1: {
            id: 2,
            name: cityB
          }
        ]
    }
    1: {
      id: 3
      name: ccc,
      title: designer,
      cities :[
          0: {
            id: 2,
            name: cityB
          }
        ]
    }
}

到这里为止一切都很好。但我想按城市groupBy 计数。

如果我按title=designer 过滤,过滤后的数据将显示,我想按城市分组并计算它。

所以我的最终结果是,

cityA = 1 counts
cityC = 2 counts

帮我解决问题。

【问题讨论】:

  • 有人可以帮忙吗?
  • 显示您的查询代码。
  • 你听说过模型和关系吗?

标签: laravel group-by count pivot-table


【解决方案1】:

您可以使用withCount 急切加载关系计数。

我假设您已经在 User.php 模型中定义了城市关系:

class User
{
    public function cities()
    {
        return $this->belongsToMany(City::class);
    }
}

然后:

$users = User::withCount('cities')->get();

我认为结果会是:

data: {
   0: {
      id: 1
      name: aaa,
      title: designer,
      cities_count: 3
    },
    1: {
      id: 2
      name: bbb,
      title: developer,
    cities_count: 2

    }
    1: {
      id: 3
      name: ccc,
      title: designer,
      cities_count: 1
    }
}

另一种方法是使用延迟加载:

$users = User::all()->loadCount('cities');

【讨论】:

    猜你喜欢
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 2018-05-20
    • 2021-08-17
    相关资源
    最近更新 更多