paulalexandru
paulalexandru

Reputation: 9530

Laravel 5 Eloquent relationships between 3 models

I have 3 models:

  1. Father
  2. Son
  3. GrandSon

The relationship is obvious, a father can have many sons and his sons can have many grandsons.

What I want to achieve is to find out how many grandsons a father has.

I know that to find out how many sons he has I have to use this:

Father::find(1)->sons->count();

But how can I find out how many grandsons he has?

Upvotes: 1

Views: 548

Answers (2)

Homme Sauvage
Homme Sauvage

Reputation: 1916

In addition to @jsphpl's answer, you can also continue chaining but with the methods instead of properties calls.

Father::find(1)->sons()->grandsons()->grandgrandsons()->count();

This is because sons() returns a relation and not a collection, so grandsons() will continue building the query from that sons() query. The same applies on grandgrandsons().

Upvotes: 1

jsphpl
jsphpl

Reputation: 5070

If you don't want to loop through the Sons, you can define a hasManyThrough relation on the Father model, like so:

class Father
{
    public function grandsons()
    {
        return $this->hasManyThrough('GrandSon', 'Son');
    }
}

Check here for reference: http://laravel.com/docs/5.1/eloquent-relationships#has-many-through

Upvotes: 1

Related Questions