Alan Flores Alan Flores - 6 days ago 6
PHP Question

BelongsToMany with BelongsToMany relation

i have this tables

providers

id

name

event_type

id

name

captions

id

name

caption_event_type

caption_id

event_type_id

caption_provider

caption_id

provider_id

Provider belongToMany Caption, and Captions belongsToMany Event_type.. now i have to get all Provider of one Event type.. how can i do that??

Answer

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!

Comments