Morph-To-Many and MorphTo #228
-
Hi, thank you @staudenmeir for this (another great) package! Currently I am trying to get my head around a complex polymorphic structure. I am extending the awesome https://github.com/spatie/laravel-permission package to have roles/permissions also attached to polymorphic resources. Examples:
I have the following structure:
The model_id and model_type in this case relate to a resource (model type other than user)
The model_id and model_type in this case relate to a resource (model type other than user)
The model_id and model_type in this case relate to a user model (default or other user model)
The model_id and model_type in this case relate to a user model (default or other user model)
The model_id and model_type in this case relate to a user model (default or other user model) Now I want to get all projects a user is associated with by this "double" polymorphic relationship. Like:
I am not sure if I really need this package but it seems like so. But I did not find examples in the docs that match my use case. Can you help me out on this? I was also looking in to your https://github.com/staudenmeir/eloquent-json-relations package. But I am not sure if this is suitable in my use case but it looks also promising. Especially by eliminating a lot of pivot tables in my case.. Thank you in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hi @nilskretschmer,
Is this the path the relationship needs to "travel"?
|
Beta Was this translation helpful? Give feedback.
-
You can define the class Project extends Model
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function users(): HasManyDeep
{
return $this->hasManyDeepFromRelations($this->roles(), (new Role())->users());
}
} Then use it to define the reverse relationship: class User extends Authenticatable
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function projects(): HasManyDeep
{
return $this->hasManyDeepFromReverse((new Project)->users());
}
} |
Beta Was this translation helpful? Give feedback.
You can define the
users()
relationship from your existing relationships:Then use it to define the reverse relationship: