relations

Hi,

I have a question:

I have 2 tables

Table PROFILE has the following fields:

id INT

user_id INT

apitype enum(‘facebook’, ‘main’)

Table USER has the following fields:

id INT

I have a field USER_ID in a table PROFILE that either stores the user’s FACEBOOK ID or the user’s SITE ID (the ID that the user has on my website; this ID comes from the table USER).

If another field, "apitype" says "facebook" then the USER_ID field for that row in the PROFILE table stores the FACEBOOK ID of the user. If "apitype" says "main", then the USER_ID field for that row in the PROFILE table stores an ID taken from the USER table.

How do I represent this in the relations function in the model - so that the relation $profile->user depends on the table column USER_ID (from PROFILE) and refers to the row in the User table that is associated with that profile ID (with Users.ID = Profile.user_id) ONLY IF apitype says "main." If "apitype" does not say "main", then that relation does not hold.

Add code below to your profile model




public function relations()

  {

     return array(

       user = array(self::HAS_ONE, 'User', 'id', 'on'=>'profile.apitype = "main"');

     );

  }



and then you will be able to added user(if exist) as:




$profile = Profile::model()->find(...);

echo $profile->user->id;//print user id