Note that there are some explanatory texts on larger screens.

plurals
  1. POShow a list of records to have a join to another table using CakePHP
    text
    copied!<p>I have an application that stores Posts and Topics and joins them using a Topic_Posts table.</p> <p>The associations for the application are as follows:</p> <pre><code>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' =&gt; array('with' =&gt; 'TopicPost') ); } Topic.php class Topic extends AppModel { public $hasMany = array( 'TopicPost' ); } TopicPost.php class TopicPost extends AppModel { public $belongsTo = array( 'Topic', 'Post' ); } </code></pre> <p>When a user views a topic e.g. <code>/topics/view/topicname</code> I want to show all the posts that contain that Topic.</p> <p>So far I have the following method in my TopicsController for the view:</p> <pre><code>public function view ( $slug ) { $topic = $this-&gt;Topic-&gt;find('first', array('conditions'=&gt;array('Topic.slug'=&gt;$slug))); $this-&gt;set('topic', $topic); $this-&gt;set('title_for_layout', $topic['Topic']['title'] . ' &amp;ndash; Topics'); $this-&gt;paginate = array ( 'Post' =&gt; array ( 'limit'=&gt;15, 'conditions'=&gt;array ( 'Post.status'=&gt;array(1,2), 'TopicPost.topic_id' =&gt; $topic['Topic']['id'], ), 'order'=&gt;array('Post.datetime'=&gt;'desc'), 'contain'=&gt;array('User'=&gt;'Profile', 'TopicPost') ) ); $posts = $this-&gt;paginate('Post'); // this one $this-&gt;set('posts', $posts); </code></pre> <p>}</p> <p>And so that I can use Posts and TopicPosts I have added: <code>public $uses = array('Topic','TopicPost','Post');</code> to the top of the controller and made all models act as containable.</p> <p>So basically I need to find Posts that have a match in the database model TopicPosts for the id of the topic I'm viewing.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload