【发布时间】:2012-04-13 13:05:18
【问题描述】:
在我的应用中,我有三个表:
Users
Profiles
Friends
用户有一个个人资料,个人资料有一个用户和许多朋友。朋友有很多个人资料。
在配置文件模型中,我有一个方法可以获取配置文件的配置文件列表(但它使用来自用户表的相关用户名。)
public function getFriends($username) {
return $this->find('all', array(
'conditions' => array(
'User.username' => $username,
'Friend.status' => 1
)
));
}
所以它应该得到一个与用户名匹配用户和朋友状态为 1 的个人资料列表。但是我该怎么做呢?
我还将发布我的关联,以便您了解数据库:
用户模型:
public $hasOne = 'Profile';
个人资料模型:
public $belongsTo = 'User';
public $hasMany = array(
'ProfileFrom'=>array(
'className'=>'Friend',
'foreignKey'=>'profile_from'
),
'ProfileTo'=>array(
'className'=>'Friend',
'foreignKey'=>'profile_to'
)
);
public $hasAndBelongsToMany = array(
'Friendship' => array(
'className' => 'Profile',
'joinTable' => 'friends',
'foreignKey' => 'profile_from',
'associationForeignKey' => 'profile_to'
)
);
public $actsAs = array('Containable');
朋友模型:
public $belongsTo = array(
'UserFrom'=>array(
'className'=>'Profile',
'foreignKey'=>'profile_from'
),
'UserTo'=>array(
'className'=>'Profile',
'foreignKey'=>'profile_to'
)
);
public $actsAs = array('Containable');
【问题讨论】:
-
它看起来比需要的要复杂一些。为什么用户 HasOne 个人资料?这使得它只是用户的一部分,所以不需要在另一个模型中分离?你不只需要两张表:用户和关系吗?在关系中只需输入friend1_id 和friend2_id 就可以了?
-
用户不一定有个人资料!但这不是这个问题的重点,而是如何从其他模型中提取条件来设置条件。
-
哦,这很简单。只要模型有关系,就可以通过
$this-> Comment->someMethod()访问其他方法和属性(假设 Post hasMany Comment,示例代码位于 Post 模型中)