2013-01-14 66 views
1

我有两个型号,PostTag这是建立在一个HABTM关系,像这样当属于后所有标签:检索编辑后

class Post extends AppModel { 
    public $hasAndBelongsToMany = array('Tag'); 
} 

class Tag extends AppModel {  
    public $hasAndBelongsToMany = array('Post'); 
} 

当编辑后,我想在输入框中显示属于该帖子的所有标签。

现在我有这个在我的职位控制器:

$this->set('tags', $this->Post->Tag->find('list')); 

但由于某些原因,它的返回标记,就是在tags表,而不是只返回属于该职位的人。

我该如何修改它才能检索属于我正在编辑的帖子的标签?

回答

0

您使用find()函数的方式意味着您需要所有行标记表。

在你的模型:

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'); 
} 

您应该使用查找功能是这样的:

$postWithTag = $this->Post->find('first', array('conditions' => array('Post.id' => $post_id),'contain'=>array('Tag'))); 

返回后与它的标签。

,如果你只希望不交,你应该把属于关联关系的PostTag模型标签:

class PostTag extends AppModel {  

/** 
* @see Model::$belongsTo 
*/ 
    public $belongsTo = array(
     'Post','Tag' 
    ); 
} 

然后使用查找功能是这样的:

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); 
    }