我有两个表,两个表中都有字段username。如何为本地表和外表指定字段名?
我想让CakePHP做这样的事
ON (`T1`.`username` = `T2`.`username`)`结果是。在不作任何更改的情况下,将使用以下条件连接表:
ON (`T1`.`id` = `T2`.`t1_id`)`仅设置'foreign_key' = 'username'属性是不够的,因为它将产生如下查询:
ON (`t1`.`id` = `t2`.`username`)`我有两个解决办法。首先是动态地使用' join‘属性和join表。在这种情况下,我可以设置本地和国外的字段。但是,如果我需要将更多的表加入到该表中,并手动加入,那么即使正确设置了这些关联,我也不能再使用joined了--我需要手动编写后续联接。因此,我每次都需要编写长连接定义,而不是使用'contain' => array('T1', 'T2', 'T3')
第二,将表的“primary_key”设置为相应的字段。它可以在模型文件或运行时完成。在我的例子中,它不能在模型中完成,因为该表通过其'id'字段也具有“正确的”关联。安装它运行时是一种情况,但我不喜欢它,因为它是不明显的,看起来像黑客。
当我问这个问题时,我觉得我遗漏了一些显而易见的东西,但现在我明白了,CakePHP就是不能做到这一点。所以我开始悬赏希望有人分享解决方案。如果不是,我将尝试读取蛋糕源并重新定义模型,一些方法添加了在关联定义中定义'foreign_key'附近的本地字段的能力。
发布于 2014-03-04 08:55:39
ForeignKey假
如果在联接条件下不使用相关模型的主键的关联,标准的方法是使用'foreignKey' => false。
即鉴于这一协会:
class Comment extends AppModel {
public $belongsTo = array(
'Profile' => array(
)
);
}将生成此sql:
SELECT ... LEFT JOIN profiles on ON (Profile.id = Comment.profile_id)指定不像这样使用foreignKey:
class Comment extends AppModel {
public $belongsTo = array(
'Profile' => array(
'foreignKey' => false
)
);
}将产生此sql(无效):
SELECT ... LEFT JOIN profiles on ON ()从这里开始,可以使用条件数组键指定所需的条件:
class Comment extends AppModel {
public $belongsTo = array(
'Profile' => array(
'foreignKey' => false,
'conditions' => array(
'Comment.username = Profile.username'
),
)
);
}(请注意,这些条件被定义为字符串),因此:
SELECT ... LEFT JOIN profiles on ON (Comment.username = Profile.username)发布于 2013-11-11 16:23:33
更新:
只需指定不想使用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
)
);
}什么是外键?
在关系数据库的上下文中,外键是一个表中唯一标识另一个表行的字段。
发布于 2014-03-04 07:20:17
当您想要检索用户和他的所有评论时,只需要一个适合您的hasMany关系的解决方案。
class User extends AppModel {
public $hasMany = array(
'Comment' => array(
'finderQuery' => 'SELECT * FROM comments Comment
LEFT JOIN users User
ON Comment.username = User.username
WHERE User.id = {__CakeID__}'
)
);
}希望它能帮上忙
https://stackoverflow.com/questions/19911052
复制相似问题