I have two models, Post and Tag which are set up in a HABTM relationship like so:
class Post extends AppModel {
public $hasAndBelongsToMany = array('Tag');
}
class Tag extends AppModel {
public $hasAndBelongsToMany = array('Post');
}
When editing a post, I would like to display all of the tags belonging to this post in an input box.
Right now I have this in my posts controller:
$this->set('tags', $this->Post->Tag->find('list'));
But for some reason it’s returning every tag that’s in the tags table, rather than returning only the ones belonging to that post.
How can I modify this so it only retrieves tags that belong to the post I’m editing?
The way that you use the find() function means you want all rows of tags table.
in your models :
You should use find function this way:
it returns Post with its tags.
if you want only tags without post you should place belongsTo relation in PostTag model:
then use the find function this way: