Get counter of objects associated with Laravel 5.x

Asked

Viewed 253 times

0

My model Project has n Pieces (which is also a template). I want to add a function or Lazy Property to know how many parts are associated with a given project.

Grateful.

2 answers

2


On your model use

class Projeto extends Model
{

    public function pecas()
    {
        return $this->hasMany('App\Peca');
    }
}

And to know the quantity use

$count = App\Projeto::find(1)->pecas->count();

2

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();
# ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.