我有一个应用程序,用户可以控制他们的财产和租赁。
以下是定义的关系:
//Team.php
/**
* A team can have many properties.
*/
public function properties():
{
return $this->hasMany(Property::class);
}//Property.php
/**
* A property can have many leases.
*/
public function leases():
{
return $this->hasMany(Lease::class);
}正如您在这里看到的,一个团队可以拥有许多属性,每个属性也可以有许多租约。
我试图弄清楚如何获得与团队相关的租约数量:
$team = Auth::user()->currentTeam;
return $team->properties->leases->count();但是,上面的代码返回一个错误:
此集合实例上不存在
属性租约。
发布于 2021-09-26 08:29:03
最后,我在hasManyThrough模型上使用了一个Team关系,如下所示:
//Team.php
/**
* Get all of the leases for the team.
*/
public function leases()
{
return $this->hasManyThrough(Lease::class, Property::class);
}然后,我可以通过以下方法简单地获得特定团队创建的租约数量:
return $team->leases()->count();发布于 2021-09-24 15:42:43
可以将此方法添加到Team.php中。
public function leasesCount(){
return count(
Team::
join('properties', 'properties.team_id', '=', 'teams.id')
->join('leases', 'leases.property_id', '=', 'properties.id')
->where('teams.id', $this->id)
->get()
);
}https://stackoverflow.com/questions/69317197
复制相似问题