abnab
abnab

Reputation: 846

how to set primary and foreign key while creating a relation

Hello I have two tables and trying to create a relationship between them.

OH_USERS (table)

user_id (key)

agents

agent_id user_id (key)

I need to get agents email from OH_USERS table but insted of using user_id as a key it uses agent_id as the key to relate two table. Due to which I dont get the right result. Is there any where we can specifically define which field to use as a key or its choosen whatever its kept in the database.

Upvotes: 1

Views: 2904

Answers (3)

sucotronic
sucotronic

Reputation: 1504

The framework already has a solution for this. In the latests releases you can specify by hand what is the key you're going to use for the relation. As explained in the doc:

In case you need to specify custom PK->FK association you can define it as array('fk'=>'pk')

In your case it'll look like the following:

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

If you don't stablish the relation this way, the framework looks for the primary key of foreign table, and use it to do the join.

Upvotes: 4

Arfeen
Arfeen

Reputation: 2623

After reading your question again:

you are fetching records from 'OH_USERS' so you need to define the relation with agent there:

'agent'=>array(self::BELONGS_TO, 'AgentModel', '' , 'on' => 't.user_id = agent.user_id'), 

This way you are telling user model to make a relation with agent model on the basis of user_id and not the default agent_id

Upvotes: 0

Owais Iqbal
Owais Iqbal

Reputation: 549

Go to agent model and define in relation this...

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

//oh_users is your model class name of user and user_id is your foriegn key in agent table..

and now you use active record in your controller like this..

$agent = Agent::model()->with('user')->find('user_id=:user_id',array('user_id'=>$userid));

and now you fetch the email of user like this...

$agent['user']['email];

it will work good..

Upvotes: 0

Related Questions