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

alleknalle's avatar

With not working on MorphTo

I've got a problem with the 'with' function on a polymorphic table.

What I've got is the following:

i'ver got 4 tables: events, event_participants, users, students and personalia. event_participants has a polymorphic relations on users and students and in the table event_participants i've got 2 extra fields 'planned' and 'present' and this table also has a belongsTo relation on an event. Personalia also has polymorphic relations on users and students.

When I create an query and use with('eventParticipants') on an event and then do another with on eventParticipants (with('user')) and then antoher with on user (with('personalia'), I don't get the personalia. Everything else works, why doesn't personalia work in this case? When I only want a user with personalia everything works, but not when I need the user from the event.

Can someone help me with this?

Event model:

public function eventParticipants()
    {
        return $this->hasMany('App\Event\Models\Eloquent\EventParticipant');
    }

EventParticipant model:

public function participantable()
    {
        return $this->morphTo();
    }

public function user()
    {
        return $this->participantable()->where('participantable_type', '=', 'App\User\Models\Eloquent\User');    
}

User model:

public function eventParticipations()
    {
        return $this->morphMany('App\Event\Models\Eloquent\EventParticipant', 'participantable');
    }

public function personalia()
    {
        return $this->morphOne('App\Personalia\Models\Eloquent\Personalia', 'personaliable');
    }

Personalia Model:

public function personaliable()
    {
        return $this->morphTo();
    }

Query:

$this->eventModel->with(['eventParticipants' => function($query)
            {
                $query = $query->with(['user' => function($query)
                    {
                        $query = $query->with(['personalia' => function($query)
                            {
                                
                            }
                        ]);
                    }
                ]);
            }
        ]);
0 likes
1 reply
alleknalle's avatar

It's working by changing the user function in EventParticipant model to:

$morph = $this->belongsTo('App\User\Models\Eloquent\User', 'participantable_id')->select('users.*')->join('event_participants', function($join)
          {
          $join->on('users.id', '=', 'event_participants.participantable_id')->where('event_participants.participantable_type', '=', 'App\User\Models\Eloquent\User');
          }, null, null, 'left outer');

Don't think it's a good solution though. Anyone else got a better solution?

Please or to participate in this conversation.