One-To-One relationships

Hi,

I had a question regarding one-one relationship mapping in Yii.I’ve read about the four relationships HAS_ONE,HAS_MANY,BELONGS_TO and MANY_MANY. Please correct if I am wrong about this. Suppose a model ‘User’ has a one-one relationship with model ‘Profile’. I wish to access the relationship bi-directionally. For this to work, I would have to do the following:

1.Define a foreign key ‘fk_user’ in ‘tbl_profile’ referencing ‘tbl_user’.

2.Define a foreign key ‘fk_profile’ in ‘tbl_user’ referencing ‘tbl_profile’.

3.Define relation in ‘User’ model as :




public function relations()

{

'profile' => array(self::HAS_ONE, 'Profile', 'profile_id'),

}



4.Define relation in ‘Profile’ model as:




public function relations()

{

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

}



I should be able to access the fields as:




$someUser->profile->fieldX

and

$someProfile->user->fieldY



So far I’ve only used the HAS_MANY/BELONGS TO-pair but HAS_ONE/BELONGS TO should work the same way. (Of course HAS_ONE will return just a single model).

Thus, If I understood this correct you should have user_id as FK in the profile relationship (in the User model).

/Tommy

Thanks for the quick reply.The ‘user_id’ is a FK in ‘Profile’ model referencing ‘User’ model.I tried the HAS_ONE-BELONGS_TO combination and it worked for bi-directional access of the relationship.Just to point out, I didn’t define a FK in ‘User’ model.FK is defined only in ‘Profile’ model with the relation as HAS_ONE in ‘User’ model and ‘BELONGS_TO’ in ‘Profile’ model.Below are the relation functions.

User model:




public function relations()

	{

		return array(

			'profile' => array(self::HAS_ONE, 'Profile', 'user_id'),	

		);

	}




Profile model:




public function relations()

	{

		return array(

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

		);

	}



Though this worked, please confirm if it is the correct way to handle a one-one relationship with bi-directional access.

Yes, that’s correct