商品の複数のカテゴリを保存したい。
私はモデルを持っています:
Category.php
public $hasAndBelongsToMany = array(
'Product' => array(
'className' => 'Product',
'joinTable' => 'product_categories',
'foreignKey' => 'category_id',
'associationForeignKey' => 'product_id',
'unique' => 'keepExisting',
)
);
Product.php
public $hasMany = array(
'ProductCategory' => array(
'className' => 'ProductCategory',
'foreignKey' => 'product_id',
'dependent' => false,
),
ProductCategory.php
public $belongsTo = array(
'Product' => array(
'className' => 'Product',
'foreignKey' => 'product_id',
),
'Category' => array(
'className' => 'Category',
'foreignKey' => 'category_id',
)
);
したがって、製品/追加ビューで、次の方法でカテゴリの一連のチェックボックスを追加します。
echo $this->Form->input('ProductCategory.category_id',array(
'label' => __('Category',true),
'type' => 'select',
'multiple' => 'checkbox',
'options' => $categories
));
ただし、これにより、ゼロがインクリメントされるのname="data[ProductCategory][category_id][]"
ではなく、次の名前を持つ一連の入力が生成されます。name="data[ProductCategory][0][category_id]"
モデルとフィールドの間にキーがある形式であれば、saveAll()? を使用できます。それは私が取得している形式であるため、request-> data を操作して、save() できるようにしたい形式にする必要があります。
私はこれを正しい方法で行っていますか?それとも、私のモデルが正しく設定されていないのでしょうか?
また、hasMany データを編集するとどうなるでしょうか。たとえば、オプションのチェックを外して別のオプションを追加するとどうなりますか? Cake は新しいレコードを追加する前に、関連するすべてのレコードを自動的に削除しますか?
編集。
本質的に私が求めているのは、これを行うためのより良い、またはより迅速な方法があり、それは現在機能しています:
if ($this->Product->save($this->request->data)) {
$this->Product->ProductCategory->deleteAll(array('ProductCategory.product_id' => $this->Product->id));
foreach ($this->request->data['ProductCategory']['category_id'] as $cat_id) {
$this->Product->ProductCategory->create();
$this->Product->ProductCategory->set(array(
'product_id' => $this->Product->id,
'category_id' => $cat_id
));
$this->Product->ProductCategory->save();
}
}