Conditional relation

I have a main table ‘Blog’ (fields: blog_id, name, type_id)

  • I got a table ‘BlogType’ (fields: type_id, name) (has all possible Blog Types)

  • I have another table for the subscriptions ‘BlogSubscription’ (fields: subscription_id, blog_id, ref_id) ==> Users & Groups can subscribe to a Blog

extra tables:

‘Users’ (fields: user_id, username)

‘Group’ (fields: group_id, name)

Now my problem is, the ‘BlogSubscription.ref_id’ is related to ‘Users’ if the ‘Blog.type_id’ equals to ‘1’, and its related to ‘Groups’ if the ‘Blog.type_id’ equals to ‘2’.

How to do this correctly so I can access the user or the group model?

Welcome to the forum.

If you want to obtain in this way, you should write the condition in the relation:


'blog' => array(self::BELONGS_TO, 'Groups', 'ref_id', 'condition' => 'type_id = 1'),

'user' => array(self::BELONGS_TO, 'Groups', 'ref_id', 'condition' => 'type_id = 2'),

But it looks like a quite bad design. I’d better do 2 different fields, blog_id and user_id. This allows you to set the foreing key and use the referential integrity.

P.s: welcome to the forum!

Thx!

And thanks for the warm welcome on the forum!

Indeed, its a bad design, I’m starting to convert my old sites to Yii, so maybe its the best time to setup my database in a better design :).

I am a quite lazy guy, so I desin the database in order to delegate the most work possible to the dbms.

If you are planning a major refactoring of database, I suggest you that lot of feature of Yii works better if each table has a primary key with one field (like autoincrement).

You can add whereever this keys, they will help a lot.