1

私には2つのモデルがPostありTag、次のように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

編集中の投稿に属するタグのみを取得するようにこれを変更するにはどうすればよいですか?

4

1 に答える 1

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

次のようにfind関数を使用する必要があります。

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

タグ付きのPostを返します。

投稿のないタグのみが必要な場合は、PostTagモデルにbelongsToリレーションを配置する必要があります。

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);
    }
于 2013-01-15T06:14:12.370 に答える