English 中文(简体)
如何在建立关系的同时设定主密钥和外国密钥
原标题:how to set primary and foreign key while creating a relation
  • 时间:2012-05-24 23:21:55
  •  标签:
  • yii

你好 我有两张桌子 想在他们之间建立一种关系

OH_USER(表格)

user_id (Key)

代理代理代理

agent_id user_id (key)

I need to get 代理代理代理 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.

问题回答

框架已对此有一个解决方案 。 您可以在最新版本中手动指定您将用于此关系的密钥 。 < a href=" http://www.yiiframerform.com/doc/ api/1.1/CApiveRecord# relations- detail" rel=“ no follow” > 如 doc 中所解释 :

如果您需要指定自定义的 PK- & gt; FK 关联, 您可以将其定义为数组( fk {gt; pk ) 。

以你的情况来看,它看起来像如下:

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

如果您不以这种方式稳定关系, 框架将寻找国外表格的主要关键, 并使用它来加入 。

转到代理模型, 并定义与此相关的...

     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..

,现在您在控制器中使用了这样的活动记录。

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

现在您可以这样获取用户的电子邮件...

$agent[ user ][ email];

它会工作良好。 。 。

在再次读完你的问题之后:

您正在从 OH_USERS 获取记录, 因此您需要定义与该地特工的关系 :

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

您正在用这种方式告诉用户模式, 以便根据用户_ id而不是默认代理服务器_ id, 与代理模型建立关系





相关问题
how to change a model safe attributes in yii

I have a CActiveRecord model, and I need to change safe attributes list in that model. I have defined the safeAttributes method inside my model, like the following : public function safeAttributes() {...

Accessing a module s action rendered output

I m writing an "Account" module which should take care of everything about accounts: registration, login/logout, user administration, password recovery, account activation, etc. So I thought it would ...

yii components: events and behaviors?

i m currently learning the yii framework and have read their documentation. but i still don t understand the components. what are these. they talk about component events and behaviors. could someone ...

Yii: Customize the results of CAutoComplete

I need to make a dropdown list using CAutoComplete. Everything is set and works fine, here is my code of the action: <?php public function actionSuggestCharacter() { if(Yii::app()->...

热门标签