CakePHP saveAll- Updating a row in mysql instead of saving as a new row

穿精又带淫゛_ 提交于 2019-12-11 12:44:25

问题


I'm trying to duplicate a particular entry in the form. I get all the column values by their form id, and trying to save it as a new row using saveAll. But instead of creating a new row, it is updating the existing entry.

Here is my code:

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;
   } 

I thought maybe since the Form name is same, it is getting updated. So I added the 'copy' string to the name of the form. Yet the old entry is only getting updated.

These are the columns of my table 'Form' and their type:

    Field            Type   

  id                int(11)             
  name              varchar(25)     
  created_by        int(11)             
  access            varchar(10)     
  created           timestamp           
  modified          timestamp               
  status            varchar(15) 

The id field is auto-increment,so I thought that If I give a save method, the id will be generated of its own.


回答1:


Cake decides whether to update an existing record or save data as a new one by the presence of the id field and the existence of this id in the database. Since you include the id, it'll always update the existing record.

You could greatly simplify your code like this:

$form = $this->read(null, $data['Form']['id']);

unset($form['Form']['id']);  // no id == new record
$form['Form']['status'] = 'Incompleted';

$this->create();
$this->save($form);

As general advice: Don't copy contents of arrays one by one into another array, especially if it's your model data. First of all it's tedious, but more importantly, if you ever add a new column to your Form table, you'll either have to hunt down all the places where that new field should be copied as well, or, more likely, you'll introduce funny bugs because that new field is missing whenever you duplicate a Form.



来源:https://stackoverflow.com/questions/1392078/cakephp-saveall-updating-a-row-in-mysql-instead-of-saving-as-a-new-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!