My Project template has n Parts (which is also a template). I want to add a function or lazy property to know how many pieces are associated with a particular project.
Thank you.
My Project template has n Parts (which is also a template). I want to add a function or lazy property to know how many pieces are associated with a particular project.
Thank you.
In your model use
class Projeto extends Model
{
public function pecas()
{
return $this->hasMany('App\Peca');
}
}
And to know the amount use
$count = App\Projeto::find(1)->pecas->count();
Your model should look like this.
class Projeto extends Model
{
public function pecas()
{
# Veja mais detalhes no manual
# http://laravel.com/docs/master/eloquent-relationships#one-to-many
return $this->hasMany('App\Peca');
}
}
class Peca extends Model
{
public function projetos()
{
return $this->belongsTo('App\Projeto');
}
}
add a new method so it can be reused like this
class Projeto extends Model
{
// ...
# Exibir o total de peças, veja mais no manual
# http://laravel.com/docs/master/eloquent#query-scopes
public function scopeTotalPecas()
{
return $this->pecas()->count();
}
}
in your controller use
# ...
$total = Projeto::find(1)->totalPecas();
# ...