mardi 28 février 2017

laravel relation hasMany accessor count()

I've got these models

Machine:

->id
->...

Server

->id
->machine_id
->is_suspended

Relations from Machine model:

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

Using this relations, when I create 2 servers (1 suspended, 1 not suspended) and calling:

dd(Machine::find(1)->free_ports_amount);

Returns 0, so for some reason the accessor doesn't work. Any idea why?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2mohKJ4
via IFTTT

Aucun commentaire:

Enregistrer un commentaire