我正在尝试复制表单中的特定条目。我按表单ID获取所有列值,并尝试使用saveAll将其保存为新行。但它不是创建新行,而是更新现有条目。
这是我的代码:
function duplicateForm($data)
{
$this->data['Form']['id']=$data['Form']['id'];
$existingForm=$this->find('all',array('conditions'=>array('Form.id'=>$this->data['Form']['id'])));
foreach($existingForm as $ex):
$this->data['Form']['name']=$ex['Form']['name']." (copy)";
$this->data['Form']['created_by']=$ex['Form']['created_by'];
$this->data['Form']['access']=$ex['Form']['access'];
$this->data['Form']['status']='Incompleted';
if($this->saveAll($this->data))
{echo "Success";}
endforeach;
}
我想也许因为Form名称是相同的,所以它正在更新。所以我将'copy'字符串添加到表单的名称中。然而旧条目只是更新。
这些是我的表格'Form'的列和它们的类型:
Field Type
id int(11)
name varchar(25)
created_by int(11)
access varchar(10)
created timestamp
modified timestamp
status varchar(15)
id字段是自动递增的,所以我认为如果我给出一个save方法,id将自己生成。
答案 0 :(得分:5)
Cake通过id
字段的存在以及数据库中是否存在此id
来决定是更新现有记录还是将数据另存为新记录。由于您包含id
,因此它将始终更新现有记录。
您可以像这样大大简化代码:
$form = $this->read(null, $data['Form']['id']);
unset($form['Form']['id']); // no id == new record
$form['Form']['status'] = 'Incompleted';
$this->create();
$this->save($form);
作为一般建议:不要将数组的内容逐个复制到另一个数组中,特别是如果它是您的模型数据。首先,这很乏味,但更重要的是,如果你在Form
表中添加一个新列,你要么必须追捕那些应该复制新字段的所有地方,要么更多很可能,你会引入有趣的错误,因为每当你复制Form
时都会丢失新的字段。