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

wcactus's avatar

"belongsTo" relation with additional condition for this model's table

Hello! The question is how to describe "belongsTo" relation with additional condition for this model's table. For example, where are 3 tables: "categories", "items" and "comments". Comments can be attached to items and categories, so we have fields "comments.category_id" and "comments.item_id". For unknown reason, if comment is attached to item, the both fields are set. So if I want to get category what comment belongs to, I have to make sure the "comments.item_id" field is null. How to properly describe category() relation in Comment model?

0 likes
1 reply

Please or to participate in this conversation.