staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

I can't get to conclude this relationship #209

Closed mittb1g closed 1 year ago

mittb1g commented 1 year ago

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.

staudenmeir commented 1 year ago

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