laravel relation hasMany accessor count()

时间:2017-02-28 07:45:11

标签: mysql laravel-5 eloquent relational-database

我有这些模型

机:

False

服务器

->id
->...

机器模型的关系:

->id
->machine_id
->is_suspended

使用这种关系,当我创建2个服务器(1个暂停,1个未暂停)并且调用:

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();
}

返回0,因此由于某种原因,访问器不起作用。知道为什么吗?

1 个答案:

答案 0 :(得分:0)

您正在调用“服务器”访问者而不是查询构建器“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();
}