Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jrdavidson's avatar

Retrieving All Related Polymorhpic Models

I'm having a problem understanding how I can grab use a specific title to retrieve all models that have won that specific title. Each title can be won by different types of models so I wanted to make sure that I apply which model type it is.

Wrestlers

 - id
- name

Tag Teams

 - id
 - name

Titles

 - id
 - name

Title_Champions

 - title_id
-  championable_id
-  championable_type
- won_at
 - lost_at

I'm wanting the data to be somewhat like this unless there is a better alternative with your suggestion.

Title_Champions

| title_id | championable_id | championable_type    | won_at     | lost_at    |
|----------|-----------------|----------------------|------------|------------|
| 1        | 1               | \App\Models\Wrestler | 2021-01-01 | null       |
| 1        | 2               | \App\Models\Wrestler | 2020-01-01 | 2021-01-01 |
| 2        | 1               | \App\Models\TagTeam  | 2021-01-01 | null       |
0 likes
3 replies
webrobert's avatar

@jrdavidson

I think the title of this thread should be more along the lines of "Having trouble structuring the database for my app"... or something... with a quick summary/story/description of what you want it to do and this attempt at the structure ☝🏼

anywho, I'll be back around... I have to step out for a bit.

kevinbui's avatar
kevinbui
Best Answer
Level 41

Checking the documentation for the many to many polymorphic relationship. You might want to define the inverse of the relationship.

class Title extends Model
{
    public function wresters()
    {
        return $this->morphedByMany(Wrestler::class, 'championable');
    }

    public function tagTeams()
    {
        return $this->morphedByMany(TagTeam::class, 'championable');
    }

    public function allWinners()
    {
        return $this->tagTeams->merge($this->wrestlers);
    }
}

And that allWinners method is to get all relevant model objects.

1 like

Please or to participate in this conversation.