Skip to content
Advertisement

How to display all nested relations in a eloquent model referencing itself in many to many?

I have a many to many relation in Partners model that is referencing itself. The pivot table partner_owners has owner_id, owned_id, percent

So a partner can own another partner and so on.

How can I query all the nested relations for a partner without knowing how many levels are there?

For example $partner = Partner::where('id', 1)->get(); if this partner is owned by two others and each of the two others are owned by some others and so on I can’t figure out a way to display them all without knowing how many levels are there.

    namespace AppModels;
    
    use IlluminateDatabaseEloquentModel;
    
    class Partners extends Model
    {
        /**
         * Owners of the partner.
         */
        public function Owners()
        {
             return $this->belongsToMany(Partner::class, 'partner_owners', 'owned_id', 'owner_id')
        }
    }

Advertisement

Answer

You could create a new method called allOwners or as you wish. In it you must add the following.

/**
 * All owners that belong to the partner.
 */
public function allOwners()
{
     return $this->belongsToMany(Partner::class, 'partner_owners', 'owned_id', 'owner_id')->with('Owners')
}

So, if you call Partner::with(‘Owners’), it will get you one level of “children”, but Partner::with(‘allOwners’) will give you as many levels as it could find.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement