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 以将其转换为我希望能够保存的形式()

我会以正确的方式解决这个问题吗?或者我的模型设置不正确?

另外,编辑 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 回答