LoginSignup
2
1

More than 5 years have passed since last update.

モデルとフォーム

Posted at

hasAndBelongsToMany

hasAndBelongsToManyでフォームを生成する方法


//Model
class Item extends AppModel {
    public $hasAndBelongsToMany = array(
        'Tag' => array(
            'className' => 'Tag',
            'joinTable' => 'items_tags',
            'foreignKey' => 'item_id',
            'associationForeignKey' => 'tag_id',
            'unique' => 'keepExisting'
        )
    );
}

class ItemTags extends AppModel {
    public $belongsTo = array(
        'Item' => array(
            'className' => 'Item',
            'foreignKey' => 'item_id',
        ),
        'Tag' => array(
            'className' => 'Tag',
            'foreignKey' => 'tag_id',
        ),
    );
}

class Tag extends AppModel {
    public $hasAndBelngsToMany = array(
        'Item' => array(
            'className' => 'Item',
            'joinTable' => 'items_tags',
            'foreignKey' => 'tag_id',
            'associationForeignKey' => 'item_id',
            'unique' => 'keepExisting'
        ),
    );
}

// Controller
class ItemController extends AppController {
    public function index() {
        $this->set('tags', $this->Item->Tag->find('list'));
    }
}

// View

echo $this->Form->input('Tag');

Controller側では、モデル名の複数形を変数名にしてViewへ渡す。
View側ではモデル名(単数形)を指定することで、表示させることが出来る。

belongsTo, hasOne

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1