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

BunWong's avatar

Eloquent relationship with condition

I have 3 tables

* type a ( class TypeA )
| id | name |

* type b ( class TypeB )
| id | name |

* product ( class Product )
| id | type | type_id | name |

Now I want to set a relationship in Product::type() to relate TypeA/TypeB according to the type field,

public function type()
{
    if ($this->type == 'a') {
        return $this->belongsTo(TypeA::class, 'type', 'type');
    } else if ($this->type == 'b') {
        return $this->belongsTo(TypeB::class, 'type', 'type');
    }
}

But it doesn't work, What should I do? Thanks.

0 likes
2 replies
BunWong's avatar

Yup! Thanks very much! ❤️❤️

Please or to participate in this conversation.