Laravel One to many trough belongsto and many to many (with pivot in between)

53 Views Asked by At

I've been looking around for a fix but couldn't find it.

The situation:

Resources are connected to an Event, multiple resources can be connected to multiple events (many to Many).

Many Interventions are connected to only 1 single event at a time (One to Many).

What am I trying to do?

I'd like to make a relation between Resources and Interventions. But... of course the resources that are linked to the event must certainly be taken into account. So there may only be resources that are specific to the event that is linked to the intervention (In the screenshot you can find a part from my UML)

In short

I want to connect many resources to my interventions, but only those that are available on the parent Event.

I've tried HasManyTrough, wityhPivot but without a success. I'd realy like to do it as much Laravelish as possible, so without custom queries, but if there are no other options, I'm open for everything.

(screenshot)Order of relation

1

There are 1 best solutions below

1
On
In Event.php model

public function eventResource ()
{
    return $this->hasMany('App\Models\EventResource','event_id','id');
}

In EventResource.php Model

public function eventDetails ()
{
    return $this->hasMany('App\Models\Resource','id','resource_id');
}

In Intervention.php Model

public function events()
{
    return $this->hasMany('App\Models\Event');
}

In your Controller 

$interventions = Intervention::has('event.eventResource.eventDetails')->with('event', 'event.eventResource', 'event.eventResource.eventDetails')->get();

Let me know in case of any syntax error.

Please try this and let me know worked or not.