how i can write own relation

i have three table

user id (pk),name,age

user_interest_relation id (pk),user_id (fk) from user_id,interest_id (fk)

interest id (pk),type

is it possible to write own relation to relate user table with user_interest_relation and interest.

If it is possible then how .

Actually i want to search user buy its interest .So how i can do it .

there are may table like this which is related to user .

I want to use all table attributes in searching .on one view.

User model:

‘userInterest’ => [self::HAS_MANY ‘UserInterestRelation’, [‘user_id’=>‘id’]]

UserInterestRelation model:

‘user’ => [self::BELONGS_TO ‘User’, 'user_id]

‘interest’ => [self::BELONGS_TO ‘Interest’, ‘interest_id’]

Interest model

‘userInterest’ => [self::HAS_MANY ‘UserInterestRelation’, [‘interest_id’=>‘id’]]

this will allow U to get from users table:

$user->userInterest // all users interest

if U want go get type for each of those, U an just do

foreach($user->userInterest as $userInterest)


   $interest = $userInterest->interest; // get interest record


From UserInterestRelations model

$userInterestRelation->user // get user record

$userInterestRelation->interest // get interest record

From Interest model

$interest->userInterest // all records related to this type

foreach($interest->userInterest as $userInterest) 


      $user = $userInterest->user // get users record

1 Like

You should be able to also create a relation that jumps straight to the interest table:

User model:

public function relations()


	return array(

		'interests' => array(self::MANY_MANY, 'Interest', 'user_interest_relation(user_id, interest_id)'),



I think gii should automatically create this for you if you have your keys properly set up.

As georaldc said, Gii can take care of this for you. If you start building your relations at the database level, then use Gii to whip up the model for you, and the relations will be handled by Yii automatically with minimal work at the code level.