雄辩的关系,以获得祖父母,曾祖父母等

I have a table "people" with these fields :

  • Name
  • mother_id
  • father_id

In mother_id and father_id, I stock other Poeple ID

I have two relationships to get the parents

public function father()
{
    return $this->belongsTo(Poeple::class, 'father_id');
}

public function mother()
{
    return $this->belongsTo(Poeple::class, 'mother_id');
}

Since I can pick up the parents directly, I wonder if it is possible with Eloquent and Laravel to recover the parents of the parents, the parents of the grandparents, etc.

Is there a relationship to do that? Or a tip?

I do not know if it's possible to do:

  • I look if the child has a parent.
  • If he has a parent, I look if his parent has a grandparents
  • And so on (maximum 4)

At the end, I create a collection with all that. It's possible ?

Nested set does not seem to work for me. I have two parents.

Thank you

There is a simple trick you can achieve this.

use $appends

protected $appends = ['father'];


public function father()
{
    return $this->belongsTo(Poeple::class, 'father_id');
}

public function mother()
{
    return $this->belongsTo(Poeple::class, 'mother_id');
}

Above code will give you the nested results with every collection.