Model relation depending on type

Hi guys,

I’m trying to achieve following.

Have a table that is related through junction table to different tables depending on type.

No problem setting up the relations but as trying to query the data I’m unable to include data to junction object.

So I have created following relation function on the junction table model class to get the data included depending on type:

    public function getTarget()


        switch ($this->target_type) {

            case static::TYPE_1:

                return $this->hasOne(Type1Pool::className(), ['id' => 'target_id']);


            case static::TYPE_2:

                return $this->hasOne(Type2Pool::className(), ['id' => 'target_id']);




Is anything like that even possible with this approach?

Please do tell me if any additional information is needed!

Best regards!

if you add a type column to the table you don’t need to manually check the types

return $this->hasOne(Type2Pool::className(), ['id' => 'target_id', 'target_type' => $type]);

perhaps if you paste schema for all your tables that would help, also can you describe what entities you have and how are you trying to associate them