显示使用CakePHP连接到另一个表的记录列表
发布时间:2020-12-13 16:44:51 所属栏目:PHP教程 来源:网络整理
导读:我有一个存储帖子和主题的应用程序,并使用Topic_Posts表连接它们. 申请的协会如下: Post.phpclass Post extends AppModel{ public $name = 'Post'; public $belongsTo = 'User'; public $hasMany = array('Answer'); // Has many topics that belong to top
我有一个存储帖子和主题的应用程序,并使用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. 解决方法
我无法让它以“正确”的方式工作.我不确定这是不是蛋糕或其他东西的错误,但分页功能只是拒绝让步..正确的方法可能是在你的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); } (请注意我在我的测试中删除了一些东西,因为我的应用程序中没有一些东西,所以不要忘记把它放回去) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |