Search code examples
phplaraveleloquenthas-and-belongs-to-many

BelongsToMany with BelongsToMany relation


I need to take data from a relation belongsToMany with belongsToMany, it would come to be so: A->B->C in my model would be providers->caption->eventType, so y need to take all providers from an event type.

model looks like:

Providers Model

Class Provider extends Model {
   public function captions() {
      return $this->belongsToMany(Caption::class);
   }
}

Captions Model

Class Caption extend Model {
   public function event_type() {
      return $this->belongsToMany(Event_type::class);
   }
   public function providers() {
      return $this->belongsToMany(Provider::class);
   }
}

Event Type Model

Class Event_type extends Model {
   public function captions() {
      return $this->belongsToMany(Caption::class);
   }
}

Database looks like:

providers

id

name

event_type

id

name

captions

id

name

caption_event_type

caption_id

event_type_id

caption_provider

caption_id

provider_id

Thnks.


Solution

  • According to my understanding our Model Structure should goes like this:

    class Provider extends Model {
        public function captions()
        {
            return $this->belongsToMany(Caption::class);
        }
    }
    
    class EventType extends Model {
        public function captions()
        {
            return $this->belongsToMany(Caption::class);
        }
    }
    
    class Caption extends Model {
        public function providers()
        {
            return $this->belongsToMany(Provider::class);
        }
    
        public function eventTypes()
        {
            return $this->belongsToMany(EventType::class);
        }
    }
    

    and to get all the providers for a EventType, you get it like this:

    $captions = EventType::find(1)->captions;
    
    foreach($captions as $caption)
    {
        $providers_arr[] = $caption->providers;
    }
    
    $providers_collection = collect($providers_arr)->unique();
    

    Hope this helps!