
本文详解如何在 laravel 中使用 `withcount()` 方法,在单次查询中为模型集合批量获取关联关系的数量,避免 n+1 查询问题,提升性能并简化代码逻辑。
在 Laravel 开发中,当需要查询某个模型(如 City)并同时获取其关联模型(如 Mobile)的数量时,若采用传统方式——先查城市列表,再对每个城市调用 $city->mobile()->count()——将触发 N+1 次数据库查询,严重拖慢接口响应速度。Laravel 提供了优雅高效的解决方案:withCount() 关系聚合方法。
✅ 正确建模:定义标准关联关系
首先,请确保模型中定义的是规范的 Eloquent 关联方法(返回 HasMany 实例),而非直接返回计数值的方法:
// app/Models/City.php
class City extends Model
{
// ✅ 正确:定义 hasMany 关系(用于 withCount 和 eager loading)
public function mobiles()
{
return $this->hasMany(Mobile::class);
}
// ❌ 不推荐:mobile_count() 方法在此场景下无需手动定义
// public function mobile_count() { ... } // 移除或保留仅作辅助用途,不参与查询优化
}⚠️ 注意:withCount('mobiles') 依赖于名为 mobiles 的关联方法名(即 mobiles()),且该方法必须返回一个 Relation 实例(如 HasMany)。方法名需与 withCount() 参数严格一致(支持蛇形命名自动推导,但显式定义更可靠)。
✅ 高效查询:使用 withCount() 一次性获取计数
修改你的 findCityWithID 方法,使用 withCount('mobiles') 替代循环计数。Laravel 会自动生成 SELECT ... COUNT(*) AS mobiles_count 子查询,并将结果作为属性注入每个模型实例:
// 在控制器中
public function findCityWithID($id)
{
$cities = City::select('id', 'name', 'state_id')
->withCount('mobiles') // ? 关键:添加此行
->where('state_id', $id)
->orderBy('name')
->get();
// ✅ 直接访问 mobiles_count 属性(自动驼峰转换)
$response = $cities->map(function ($city) {
return [
'id' => $city->id,
'name' => $city->name, // 注意:原答案中误写为 $city->state,应为 $city->name
'state_id' => $city->state_id,
'mobile_count' => $city->mobiles_count // Laravel 自动添加的属性(snake_case → camelCase)
];
})->toArray();
return response()->json($response);
}✅ 输出示例 JSON:
[
{
"id": 1,
"name": "Shanghai",
"state_id": 2,
"mobile_count": 42
},
{
"id": 3,
"name": "Guangzhou",
"state_id": 2,
"mobile_count": 17
}
]? 进阶技巧与注意事项
- 多关联计数:可同时统计多个关联,如 withCount(['mobiles', 'users', 'posts']),对应属性为 mobiles_count, users_count, posts_count。
-
带条件的计数:支持闭包约束,例如仅统计启用的手机号:
->withCount(['mobiles' => function (Builder $query) { $query->where('status', 'active'); }]) -
别名重命名:使用 as 自定义计数字段名:
->withCount(['mobiles as active_mobiles' => function ($q) { $q->where('status', 'active'); }]) // → 属性名为 $city->active_mobiles - 性能对比:withCount() 底层使用 LEFT JOIN + COUNT 或子查询(取决于数据库和关联类型),全程仅 1 次 SQL 查询;而循环 count() 在 100 个城市时将执行 101 次查询。
✅ 总结
withCount() 是 Laravel 中处理“主模型 + 关联数量”场景的标准、高性能方案。它要求模型定义规范的关联方法,通过链式调用即可在结果集中自动注入计数字段,彻底规避 N+1 问题。务必避免在查询逻辑中手动调用 count(),也无需额外编写 mobile_count() 访问器——让 Eloquent 为你完成优化。










