如何在CakePhp中创建一元关联? [英] How do I create a Unary association in CakePhp?
问题描述
在Cake中创建一元关联有快捷方式吗?
Is there a shortcut for creating Unary associations in Cake?
例如,用户是另一个用户的朋友。
For example, a user is a friend of another user. I'm pretty sure it's going to violate cake's conventions if I try it the hard way and code the associations myself.
蛋糕有HABTM:
var $hasAndBelongsToMany = array(
'User' =>
array(
'className' => 'User',
'joinTable' => 'friends',
'foreignKey' => 'user_id',
'associationForeignKey' => 'friend_id',
'unique' => true
)
);
这会有效吗?
更新:
如何立即保存数据?
Update: How do I save the data now?
$this->data["Friend"] = $request["Requester"];
$this->data["Admirer"] = $request["Requestee"];
$this->Friend->create();
$this->Friend->save($this->data);
$ request [Requester]和$ request [Requestee]都持有User类型的对象。
HABTM rel在用户模型中定义
$request["Requester"] and $request["Requestee"] both hold objects of type User. The HABTM rel is defined in the User model
var $hasAndBelongsToMany = array(
'Friend' => array(
'className' => 'Friend',
'joinTable' => 'friends',
'foreignKey' => 'user_id',
'associationForeignKey' => 'id'
),
'Admirer'=>array(
'className'=>'Friend',
'joinTable'=>'friends',
'foreignKey' => 'friend_id',
'associationForeignKey' => 'id',
)
);
所有这一切都是$ data - > [Friend]的ID存储在id列
All that happens is the $data->["Friend"]'s id is stored in the id column of the friends table
推荐答案
这是我在示例应用程序中使用的解决方案
Here is a solution I use in an example application
需要两个表,用户和关注者。重要的字段是User-> id,Follower-> user_id,Follower-> friend_id。
Two tables are needed, users and followers. The important fields are User->id, Follower->user_id, Follower->friend_id.
我希望此代码段有所帮助。
I hope this snippet helps.
<?php
class User extends AppModel {
public $useTable='users';
public $hasAndBelongsToMany=array(
'Friend'=>array(
'className'=>'User',
'joinTable'=>'followers',
'foreignKey' => 'user_id',
'associationForeignKey' => 'friend_id',
),
'Admirer'=>array(
'className'=>'User',
'joinTable'=>'followers',
'associationForeignKey' => 'friend_id',
'foreignKey' => 'user_id',
),
);
}
-teh
这篇关于如何在CakePhp中创建一元关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!