Yar*_*lav 4 php cakephp cakephp-model cakephp-2.3
我有两个表都有字段username.我如何为本地和外国表指定字段名称?
我想CakePHP会做类似的事情
ON (`T1`.`username` = `T2`.`username`)`
Run Code Online (Sandbox Code Playgroud)
结果.如果没有任何更改,表将加入以下条件:
ON (`T1`.`id` = `T2`.`t1_id`)`
Run Code Online (Sandbox Code Playgroud)
设置'foreign_key' = 'username'属性是不够的,因为它会产生这样的查询:
ON (`t1`.`id` = `t2`.`username`)`
Run Code Online (Sandbox Code Playgroud)
我有两个解决方案.第一个是使用'join'属性并动态连接表.在这种情况下,我可以设置本地和外地字段.但是,如果我需要将更多表连接到那个表,手动加入,我不能再使用包含我需要手动编写以下连接,即使这些关联设置正确.所以我需要每次编写长连接定义而不是使用'contain' => array('T1', 'T2', 'T3')
其次是将表的'primary_key'设置为相应的字段.它可以在模型文件中或在运行时中完成.在我的情况下,它不能在模型中完成,因为该表也通过其'id'字段具有"正确"关联.设置运行时是这样的,但我不喜欢它,因为它不明显,看起来像一个黑客.
当我问这个问题时,我以为我错过了一些明显的东西,但现在我明白CakePHP就是不能这样做.所以我开始了一个赏金,希望有人分享解决方案.如果不是,我将尝试读取蛋糕源并重新定义模型的一些方法,以添加'foreign_key'在关联定义附近定义本地字段的能力.
AD7*_*six 13
要在关联条件中使用不使用相关模型的主键的关联 - 标准方法是使用'foreignKey' => false.
即,这种关联:
class Comment extends AppModel {
public $belongsTo = array(
'Profile' => array(
)
);
}
Run Code Online (Sandbox Code Playgroud)
会生成这个sql:
SELECT ... LEFT JOIN profiles on ON (Profile.id = Comment.profile_id)
Run Code Online (Sandbox Code Playgroud)
指定不要像这样使用foreignKey:
class Comment extends AppModel {
public $belongsTo = array(
'Profile' => array(
'foreignKey' => false
)
);
}
Run Code Online (Sandbox Code Playgroud)
会产生这个(无效的)sql:
SELECT ... LEFT JOIN profiles on ON ()
Run Code Online (Sandbox Code Playgroud)
从这一点开始,可以使用条件数组键指定所需的条件:
class Comment extends AppModel {
public $belongsTo = array(
'Profile' => array(
'foreignKey' => false,
'conditions' => array(
'Comment.username = Profile.username'
),
)
);
}
Run Code Online (Sandbox Code Playgroud)
(注意条件定义为字符串)导致:
SELECT ... LEFT JOIN profiles on ON (Comment.username = Profile.username)
Run Code Online (Sandbox Code Playgroud)
更新:
只需指定您不想使用foreignKey,然后指定条件(所有条件都在关联中:
'foreignKey' => false 和 'conditions' => 'Comment.username = User.username'
PS - 可能是个好主意,不要对帮助你的人不礼貌.
CakePHP书中非常清楚地定义了这一点:http: //book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany
class User extends AppModel {
public $hasMany = array(
'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'user_id', // <---- THIS HERE you can define the foreign_key
'conditions' => array('Comment.status' => '1'),
'order' => 'Comment.created DESC',
'limit' => '5',
'dependent' => true
)
);
}
Run Code Online (Sandbox Code Playgroud)
在关系数据库的上下文中,外键是一个表中的一个字段,它唯一地标识另一个表的一行.