Laravel获取Team嵌套关联的Lease总数时报错,该如何正确实现?
报错原因
$team->properties返回的是Team关联的所有Property实例组成的集合对象,不是单个Property模型,集合类本身没有定义leases属性,访问不存在的属性就会抛出对应报错。
正确统计方案
推荐优先使用Laravel自带的**远层一对多关联(hasManyThrough)**实现,该方案直接通过SQL统计,无需加载中间模型,性能最优:
- 首先在
Team.php中新增远层关联定义:
// Team.php /** * 定义团队到租约的远层一对多关联 */ public function leases() { return $this->hasManyThrough(Lease::class, Property::class); }
- 统计时直接调用关联的count方法即可:
$team = Auth::user()->currentTeam; return $team->leases()->count();
如果不想新增关联,也可以用集合方法处理,仅适合小数据量场景:
// 方案1:合并所有 property 下的租约集合后统计 return $team->properties->flatMap(fn($property) => $property->leases)->count(); // 方案2:逐个统计每个 property 的租约数后求和 return $team->properties->sum(fn($property) => $property->leases()->count());
内容的提问来源于stack exchange,提问作者oliverbj
相关产品推荐
相关产品推荐

