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 :
class Post extends AppModel {
/**
* @see Model::$actsAs
*/
public $actsAs = array(
'Containable',
);
public $hasAndBelongsToMany = array('Tag');
}
class Tag extends AppModel {
/**
* @see Model::$actsAs
*/
public $actsAs = array(
'Containable',
);
public $hasAndBelongsToMany = array('Post');
}
You should use find function this way:
$postWithTag = $this->Post->find('first', array('conditions' => array('Post.id' => $post_id),'contain'=>array('Tag')));
it returns Post with its tags.
if you want only tags without post you should place belongsTo relation in PostTag model:
class PostTag extends AppModel {
/**
* @see Model::$belongsTo
*/
public $belongsTo = array(
'Post','Tag'
);
}
then use the find function this way:
class PostController extends AppController {
/**
* @see Controller::$uses
*/
public $uses = array(
'Post', 'PostTag'
);
public function post(){
/**
* Your code
*/
$tags = $this->PostTag->find('all', array('conditions' => array('PostTag.post_id' => $post_id)));
$this->set('tags',$tags);
}