MorphOneThrough Relationship #38944
-
I know the MorphOneThrough relationship does not currently exist in the latest version of Laravel however I have a need for something like this. Has anyone else had a need for something like this and can share how they were able to handle this? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 11 replies
-
What do the tables involved look like? |
Beta Was this translation helpful? Give feedback.
-
You can actually build this relationship yourself: class Title extends Model
{
public function modelA()
{
return $this->hasOneThrough(ModelA::class, TitleChampionship::class, null, 'id', null, 'champion_id')
->where('champion_type', ModelA::class);
}
} |
Beta Was this translation helpful? Give feedback.
-
Laravel doesn't support this kind of relationship because the SQL query would have to join a different table depending on the value of I created a package for complex cases like this that allows you to merge multiple relationships, but it requires a bit of setup: In your case, you would merge the two |
Beta Was this translation helpful? Give feedback.
-
Any updates on this? I need a morphOneThrough as well... |
Beta Was this translation helpful? Give feedback.
Laravel doesn't support this kind of relationship because the SQL query would have to join a different table depending on the value of
champion_type
and that's not possible.I created a package for complex cases like this that allows you to merge multiple relationships, but it requires a bit of setup:
https://github.com/staudenmeir/laravel-merged-relations
In your case, you would merge the two
HasOneThrough
relationshipsmodelA
andmodelB
. Also, the package currently doesn't offer a way to only return a single related result, only a collection. You would have to manually take the first collection item (e.g. with an accessor).