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側ではモデル名(単数形)を指定することで、表示させることが出来る。