【发布时间】:2012-11-15 10:55:28
【问题描述】:
我想为一个产品保存多个类别。
我有模型:
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() 吗? 因为它是我得到的格式,所以我必须操纵请求->数据以将其转换为我希望能够保存的形式()
我是否以正确的方式解决这个问题?或者我的模型设置不正确?
另外,编辑 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();
}
}
【问题讨论】:
标签: cakephp