Get counter of objects associated with Laravel 5.x

0

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.

    
asked by anonymous 09.07.2015 / 04:00

2 answers

2

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();
    
10.07.2015 / 20:26
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();
# ...
    
10.07.2015 / 20:42