我有一个名为user_relationship的表。它有两个外键,引用回User表来映射它们是朋友。
CREATE TABLE `user_relationships` (
`id` int(11) unsigned NOT NULL auto_increment,
`status` varchar(255) default 'pending',
`time` datetime default NULL,
`user_id` int(11) unsigned NOT NULL,
`friend_id` int(11) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_user_relationships_users1` (`user_id`),
KEY `fk_user_relationships_users2` (`friend_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
当我尝试烘焙时,自然不明白friend_id必须引用用户模块。我想手动编辑代码但是在理解下面要编辑的部分时遇到一些问题
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Friend' => array(
'className' => 'Friend',
'foreignKey' => 'friend_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
在这部分代码中,我想将friend_id引用到用户表
'Friend' => array(
'className' => 'Friend',
'foreignKey' => 'friend_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
我试过这样做..我还需要改变其他什么吗?
'Friend' => array(
'className' => 'Friend',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
答案 0 :(得分:2)
这个怎么样?
class UserRelationship {
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
),
'Friend' => array(
'className' => 'User',
'foreignKey' => 'friend_id'
)
);
}
class User {
var $hasAndBelongsToMany = array(
'Friend' => array(
'className' => 'User',
'joinTable' => 'user_relationships',
'foreignKey' => 'user_id',
'associationForeignKey' => 'friend_id',
'with' => 'UserRelationship'
)
);
}
可以从不同的角度看待关联:
User <- Relationship -> User
| | |
hasMany belongsTo |
Relationship <- User (user_id) hasMany
| User (friend_id) -> Relationship
| |
HABTM HABTM
User <----------------------> User
您的“物理”布局(即数据库架构)为User -> Relationship -> User
。你真正想要的关系是User -> User
关系。从技术上讲,转换为User hasAndBelongsToMany User
关联(也称为多对多)。由于它使用三种模型,因此可以将多对多关联分解为:
你不需要 hasAndBelongsToMany关联,但这是你真正想要的。你根本不需要关系模型,因为它只是连接两个用户的辅助模型,但如果你做想要指定它的关联,它有两个belongsTo关联。 / p>
答案 1 :(得分:1)
“朋友”的类名是错误的。由于您没有“朋友”表,因此没有“朋友”模型,您可以引用“用户”类,因为它们共享同一个表。
'Friend' => array(
'className' => 'User',
'foreignKey' => 'friend_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
答案 2 :(得分:1)
我能够侥幸逃脱:
class User extends AppModel {
var $hasAndBelongsToMany = array(
'Friends1' => array(
'className' => 'User',
'joinTable' => 'friends',
'foreignKey' => 'user_id',
'associationForeignKey' => 'friend_id',
'with' => 'Friend'
),
'Friends2' => array(
'className' => 'User',
'joinTable' => 'friends',
'foreignKey' => 'friend_id',
'associationForeignKey' => 'user_id',
'with' => 'Friend'
)
);
function afterFind(array $results) {
// Merge both sides of the relationship into one alias
foreach ($results as $key=>$result) {
if (isset($result["Friends1"]) && isset($result["Friends2"])) {
$results[$key]["Friends"] = array_merge($result["Friends1"], $result["Friends2"]);
unset($results[$key]["Friends1"]);
unset($results[$key]["Friends2"]);
}
}
它很乱,但你明白了:抓住关系的两边,然后在数据库读取后合并它们:)