staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

I can't get to conclude this relationship

mittb1g opened this issue · comments

I have three models.

Portal
Module
Field

Portal <- Many to Many (config_portals_modules pivot table) -> Module
Module -> MorphMany -> Field (field has the columns model_type and model_id )
Field -> BelongsTo -> Portal (Field has the column portal_id)

I need in the Portal model to define the modules() relation that brings the modules with all the fields that have portal_id equal to the id of the portal being queried.

It would be something like this:
Portal model:
...

public function modules()
{
  return $this->hasMany(Module::class)->with(['fields' => function ($query) {
    $query->where('portal_id', $this->id);
}]);
}

What's the problem with this approach, that I can't call it statically, example:

Portal::where('subdomain', 'test')->with('modules')->get();

The value of $this->id will be null for this case, and will not bring me any field.

Hi @mittb1g,
Unfortunately, I don't see a way to make this work with eager loading.