3

商品の複数のカテゴリを保存したい。

私はモデルを持っています:

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

2 に答える 2

1

フォーム内で、次の行に沿って表示したいだけ繰り返します

for/while/do()
{       
    $counter++
    $this->Form->text('Product.'.$counter.'.price');
    $this->Form->text('Product.'.$counter.'.description');

}
于 2012-11-15T16:09:43.530 に答える
0

saveAll()IDがデータに含まれており、正しくフォーマットされていると仮定して、レコードとそれに関連するすべてのレコードを自動的に保存するように設計されているため、これを使用します。

http://book.cakephp.org/2.0/en/models/ Saving-your-data.html#model-saveall-array-data-null-array-options-array

于 2012-11-15T11:35:48.120 に答える