我有一个名为 user_relationship 的表。它有两个外键引用用户表来映射他们是朋友。
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' => ''
)
这个怎么样?
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 关联,但这是您真正想要的。您实际上根本不需要关系模型,因为它只是连接两个用户的辅助模型,但如果您do也想指定其关联,那么它有两个belongsTo关联。
'Friend' => array(
'className' => 'User',
'foreignKey' => 'friend_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
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"]);
}
}
这很混乱,但你明白了:抓住关系的双方,然后在数据库读取后合并它们:)