我有一个存储帖子和主题并使用 Topic_Posts 表连接它们的应用程序。
该应用程序的关联如下:
Post.php
class Post extends AppModel
{
public $name = 'Post';
public $belongsTo = 'User';
public $hasMany = array('Answer');
// Has many topics that belong to topic post join table... jazz
public $hasAndBelongsToMany = array(
'Topic' => array('with' => 'TopicPost')
);
}
Topic.php
class Topic extends AppModel
{
public $hasMany = array(
'TopicPost'
);
}
TopicPost.php
class TopicPost extends AppModel {
public $belongsTo = array(
'Topic', 'Post'
);
}
例如,当用户查看主题时/topics/view/topicname
,我想显示包含该主题的所有帖子。
到目前为止,我的 TopicsController 中有以下方法用于视图:
public function view ( $slug )
{
$topic = $this->Topic->find('first', array('conditions'=>array('Topic.slug'=>$slug)));
$this->set('topic', $topic);
$this->set('title_for_layout', $topic['Topic']['title'] . ' – Topics');
$this->paginate = array
(
'Post' => array
(
'limit'=>15,
'conditions'=>array
(
'Post.status'=>array(1,2),
'TopicPost.topic_id' => $topic['Topic']['id'],
),
'order'=>array('Post.datetime'=>'desc'),
'contain'=>array('User'=>'Profile', 'TopicPost')
)
);
$posts = $this->paginate('Post'); // this one
$this->set('posts', $posts);
}
这样我就可以使用我添加的 Posts 和 TopicPosts:public $uses = array('Topic','TopicPost','Post');
到控制器的顶部,并使所有模型都作为可包含的。
所以基本上我需要在数据库模型 TopicPosts 中找到与我正在查看的主题的 id 匹配的帖子。