我有这些模型
机器:
->id
->...
服务器
->id
->machine_id
->is_suspended
与机器模型的关系:
public function servers()
{
return $this->hasMany('App\Server');
}
//with suspended servers
public function getFreePortsAmountAllAttribute()
{
return $this->servers->count();
}
//without suspended servers
public function getFreePortsAmountAttribute()
{
return $this->servers->where('servers.is_suspended', false)->count();
}
使用这种关系,当我创建 2 个服务器(1 个暂停,1 个未暂停)并调用时:
dd(Machine::find(1)->free_ports_amount);
返回 0,因此由于某种原因访问器无法工作。知道为什么吗?
最佳答案
您正在调用“servers”访问器而不是查询构建器“servers()”,请尝试以下更改:
//with suspended servers
public function getFreePortsAmountAllAttribute()
{
return $this->servers()->count();
}
//without suspended servers
public function getFreePortsAmountAttribute()
{
return $this->servers()->where('is_suspended', false)->count();
}
关于mysql - laravel 关系 hasMany 访问器 count(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42502916/