我有一个存储帖子和主题的应用程序,并使用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’);到控制器的顶部,使所有模型都可以包含.
解决方法
我无法让它以“正确”的方式工作.我不确定这是不是蛋糕或其他东西的错误,但分页功能只是拒绝让步..正确的方法可能是在你的Post模型中编写自己的paginate函数,有一些信息如何在食谱中做到这一点.
同时,我为您提供以下解决方法.它不是最优的(至少不是没有缓存)但它有效.如果遇到性能问题,可以以正确的方式执行此操作,但在此之前,下面的代码应该执行此操作.
public function view ( $slug ) { $topic = $this->Topic->find('first',$topic['Topic']['title'] . ' – Topics'); // step 1: get post IDs related to your topic $postIDs = $this->Topic->TopicPost->find ( 'list',array ( 'fields' => array('TopicPost.post_id'),'conditions' => array('TopicPost.topic_id' => $topic['Topic']['id']) ) ); $this->paginate = array ( 'Post' => array ( 'limit'=>15,'conditions'=>array ( 'Post.status' => array(1,// step 2: include them in your paginate conditions 'Post.id' => $postIDs,'order' => array('Post.datetime'=>'desc'),) ); $posts = $this->paginate('Post'); $this->set('posts',$posts); }
(请注意我在我的测试中删除了一些东西,因为我的应用程序中没有一些东西,所以不要忘记把它放回去)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。