HAS_ONE Relationsip Insert

I have 2 class,



‘memberships’ => array(self::HAS_ONE, ‘Membership’, ‘id’),



‘user’ => array(self::BELONGS_TO, ‘User’, ‘user_id’),

A user has only one membership. Is it possible to create membership with same user_id? How i can avoid it? Is it by assign user_id column in Membership class to unique? Sorry still newb here!

You probably want to use Foreign Keys.


Did you mean like this?

'user' => array(self::BELONGS_TO, 'User', 'ForeignKey', 'user_id'),

I think the best solution currently is add on Membership rules like this

           array('user_id', 'unique','className' => 'User' ,'attributeName' => 'id'),

Hi gezzeg, I haven’t personally used CUniqueValidator that way. Does it work?

However, imho, if I get it well, I suppose many users can have the same membership, right? So I’d design my classes like this:

User(id,username,password, membershipId)

And 1-to-many relationship in User:

'membership' => array(self::BELONGS_TO, 'Membership', 'membershipId'),

And in Membership model:

'users' => array(self::HAS_MANY, 'User', 'userId'),

What do you think? There wouldn’t be any unique validation needed. Of course, that won’t work if by any chance you want to keep track of membership evolution of some user (like they do in airlines: BLUE, SILVER, GOLD, etc.). In that case, a many-to-many relationship is needed.

Hahaha. Thank you. Im already make mistake when defining the scheme. My mistake hahaha . Thanks!

But using CUniqueValidator that way can also can be use. I have found some example on this forum.