我有3个表:- users订阅(默认情况下应该是posts_users (n-n))
订阅表是此关系所需的n表。我不想叫它"posts_users“,因为它对我的系统来说是非常混乱的,因为我有更多的用户和帖子之间的关系。
为了创建hasAndBelongsToMany关系,我执行了以下操作:
员额(模式):
public $hasAndBelongsToMany = array(
'Subscriptions' => array(
'className' => 'User',
'joinTable' => 'subscriptions',
'foreignKey' => 'post_id',
'associationForeignKey' => 'user_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);用户(模型):
public $hasAndBelongsToMany = array(
'Post' => array(
'className' => 'Post',
'joinTable' => 'subscriptions',
'foreignKey' => 'user_id',
'associationForeignKey' => 'post_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);假设我想用id 3为用户查找订阅的帖子。有什么方法可以做查找来为用户检索订阅帖子的数据吗?我应该在哪个模型中进行查询?怎么做??
谢谢。
发布于 2012-10-17 10:26:10
好的。我终于明白了。
您可以从这两个相关模型中的任何一个进行查询。在本例中,Post或用户。
$this->Post->User->find('all', array(
'conditions' => array('User.id' => $this->Session->read('Auth.User.id')),
'contain' => array('Subscriptions')
));这将返回当前用户的订阅票证(在订阅数组中)。
https://stackoverflow.com/questions/12931604
复制相似问题