In your PostsController, set a variable $posts
with find(‘all’)
query to return an object containing all posts and records relating to the Post
model, your method may look something like:
PostsController:
public function view() {
if (!$this->Post->exists()) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('posts', $this->Post->find('all'));
}
Then in your view, just iterate over $posts to display the title and related comments.
Posts/view.ctp:
<?php foreach ($posts as $post): ?>
<h3><?php echo $post['Post']['title']; ?></h3>
<?php foreach ($post['Comment'] as $comment):?>
<p><?php echo $comment['comment'];?></p>
<?php endforeach;?>
<?php endforeach;?>
See Retrieving your data and Additional methods and properties
From the documentation:
If the id is not provided with exists(), it calls Model::getID() to
obtain the current record id to verify, and then performs a
Model::find('count') on the currently configured datasource to
ascertain the existence of the record in persistent storage.
You should always have some sort of exception thrown if no records exist in the database.