【问题标题】:Laravel query wtih goupby & countLaravel 查询与分组和计数
【发布时间】:2021-11-21 01:08:00
【问题描述】:

我有三个表,分别称为国家、州和城市。

国家表架构:

id
country_name

状态表架构:

  id
  state_name
  country_id

城市表架构:

  id
  city_name
  state_id
  country_id

现在我需要像这样输出:

{
country_name: United States,
states counts of all states in the country,
cities: counts of all cities in the country
}

【问题讨论】:

    标签: mysql laravel laravel-query-builder


    【解决方案1】:
          select cc.country_name , 
                 count (distinct s.id) count_states ,
                 count(distinct c.id)  count_cities
      from Cities c 
      inner join states s on s.id = c.state_id
      inner join countries cc on cc.id = s.country_id
    

    我的方式:简单地加入所有并使用 distinct 来计算州和城市 ID

    【讨论】:

      【解决方案2】:

      在控制器中

      Countries::withCount(['states','cities'])->get();
      

      国家模式

      public function states()
      {
          return $this->hasMany(States::class, 'country_id', 'id');
      }
       public function cities()
      {
          return $this->hasMany(Cities::class, 'country_id', 'id');
      }
      

      【讨论】:

        猜你喜欢
        • 2021-11-04
        • 2016-02-10
        • 1970-01-01
        • 2011-01-29
        • 1970-01-01
        • 2022-01-08
        • 2021-07-04
        • 2016-07-12
        • 2016-02-18
        相关资源
        最近更新 更多