I'm new to CakePHP
and just want to display a list of associated tags in a post's view.
I have searched all over the web and nothing seems to work.
This is what I have at the moment:
// PostController
public function view($id = null) {
$this->set('tags', $this->Post->Tag->find('all', array('conditions' => array('PostTag.post_id' => $id))));
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('post', $post);
}
// Post's view.ctp
echo $this->Text->toList($tags);
This is the error I'm getting:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'PostTag.post_id' in 'where clause'
This should be so easy but I am completely stuck.
Thanks to anyone who can help!
Finally! After finding another question here about joining tables and some experimentation, I got it to work.
public function view($id = null) {
$options = array(
'joins' => array(
array('table' => 'posts_tags',
'alias' => 'PostTags',
'type' => 'left',
'conditions' => array(
'Post.id = PostTags.post_id'
)
),
array('table' => 'tags',
'alias' => 'Tag',
'type' => 'left',
'conditions' => array(
'PostTags.tag_id = Tag.id'
)
)
)
,'conditions' => array(
'PostTags.post_id' => $id
)
,'fields' => array(
'Tag.title' // the name of the tag
)
,'recursive' => -1
);
$tagsList = $this->Post->find('all', $options);
// added $result and foreach to ensure that all results would be printed
$result = array();
foreach ($tagsList as $tag):
array_push($result, $tag['Tag']['title']);
endforeach;
$this->set('tags', $result);
// ... rest of the call to find the post info
}
// Post's view.ctp
echo $this->Text->toList($tags);
Before I added $result, it would only print out the first association. I used "echo pr($tags);" in my view and found that the results I wanted were nested inside two arrays. After I added the foreach, it would correctly list all of the assigned tags in my view.
Is the Tag model loaded in your Post controller? How about simply:
$this->set('tags', $this->Tag->find('all', array('conditions' => array('Tag.post_id' => $id))));