You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel使用groupBy与count实现国家州城市三表统计查询

Laravel 查询构造器实现国家关联统计方案

下面分两种常用实现方式:

方式1:基于模型关联实现(推荐,代码更简洁)

首先需要在 Country 模型中定义对应关联关系:

// App/Models/Country.php
class Country extends Model
{
    // 关联州表
    public function states()
    {
        return $this->hasMany(State::class);
    }

    // 关联城市表
    public function cities()
    {
        return $this->hasMany(City::class);
    }
}

之后直接调用 Laravel 自带的 withCount 方法即可完成统计:

$stats = Country::select('id', 'country_name')
    ->withCount(['states', 'cities'])
    ->get();

返回结果中每个对象将包含 country_name、states_count、cities_count 三个核心字段,符合输出要求。

方式2:原生查询构造器实现(无需定义模型关联)

如果不想提前定义关联,可以直接用 join + 聚合函数实现:

use Illuminate\Support\Facades\DB;

$stats = DB::table('countries')
    ->select(
        'countries.country_name',
        DB::raw('COUNT(DISTINCT states.id) as states_total'),
        DB::raw('COUNT(DISTINCT cities.id) as cities_total')
    )
    ->leftJoin('states', 'countries.id', '=', 'states.country_id')
    ->leftJoin('cities', 'countries.id', '=', 'cities.country_id')
    ->groupBy('countries.id', 'countries.country_name')
    ->get();

注意:这里必须用 DISTINCT 去重统计id,否则多表join产生的笛卡尔积会导致统计结果偏大。

内容的提问来源于stack exchange,提问作者Abdullah Al Mamun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 11:54:03