Search code examples
laraveleloquentlaravel-8eloquent-relationship

Eloquent relationship between two models that belong to the same model


I have a many-to-many relationship between Parent and Child but I don't know yet how to express that using Eloquent relationships.

Database visualisation

class Child extends Model
{
    public function family()
    {
        return $this->belongsTo(Family::class);
    }
}
class Parent extends Model
{
    public function family()
    {
        return $this->belongsTo(Family::class);
    }
}

(I know I can't name a class Parent in PHP, I just dont wanna reveal all my database)

class Family extends Model
{
    public function parents()
    {
        return $this->hasMany(Parent::class);
    }

    public function children()
    {
        return $this->hasMany(Child::class);
    }  }
}

I need to set relationships between Child and Parent through Family.

Until now I'm doing:

App\Models\Child::find(1)->family->with(['parents'])->get()

Solution

  • public function parents()
    {
        return $this->hasManyThrough(Parent::class, Family::class, 'id', 'family_id', 'family_id', 'id');
    }