我正在尝试复制表单中的特定条目.我按表单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将自己生成.
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.