如何添加一个有多个关系层的数据计数



我有2个表位置和客户的关系是有很多。一个位置可以有很多客户

所以我想要的是获得一个位置以及在该位置注册了多少客户

在我的LocationController我有这个代码

return $this->location::withCount(["customer"])->select('location_id')->whereLocationId($data->location_id)->first();

和位置模型

public function customer()
{
return $this->hasMany(Customer::class);
}

返回的是location_id,没有客户数

可以使用withCount()雄辩方法

https://laravel.com/docs/9.x/eloquent-relationships counting-related-models

最新更新