CakePHP – 在Model-> beforeSave()中从插入更改为更新
这是我的beforeSave功能. checkExisting()检查$this->数据中的某些字段是否唯一,如果没有现有记录,则返回false,如果存在,则返回现有记录的ID.这个功能工作正常.
public function beforeSave(){ if ($this->checkExisting() !== false){ $this->id = $this->checkExisting(); } return true; } 我认为我的代码应该做的是:如果有现有记录,请将Model-> id设置为该现有记录的ID,因此强制CakePHP更新而不是插入. 这个代码实际上做的是插入新记录,无论如何. 如果我更改$this-> id = $this-> checkExisting(); to $this-> data [‘Model’] [‘id’] = $this-> checkExisting();,MySQL给出了一个错误(主键的重复值),因为Cake还在尝试插入,而不是而不是更新,数据. Cake在什么阶段决定插入而不是更新? beforeSave()来不及影响这个决定吗? 编辑 – 这是我的控制器代码: public function add(){ if (!empty($this->data)){ $saved = 0; foreach($this->data['Attendance'] as $att){ $this->Attendance->create(); if ($this->Attendance->save(array('Attendance'=>$att))){ $saved++; } if ($saved > 0){ $this->Session->setFlash('Data saved successfully','success'); }else{ $this->Session->setFlash('No data was saved. Please make sure you have entered some data.','failure'); } } } } 考虑一下,是否与我明确调用Attendance :: create()这一事实有关? 解决方法
不,之前保存为时尚晚,无法改变这一点. Model-> save()按顺序执行以下操作:
>调用Model-> set(),传递提供的数据.这将提取一个id并设置Model-> id 假设checkExisting()行为正确,上面的代码应该可以正常工作.我再看看你的checkExisting()代码. 另请注意,在对checkExisting()进行两次调用时,代码效率很低.这会更好: $existing = $this->checkExisting(); if($existing) { $this->id = $existing; } 编辑 public function add() { if(!empty($this->data)) { if($this->Attendance->saveAll($this->data)) { $this->Session->setFlash('Data saved successfully','success'); } else { $this->Session->setFlash('No data was saved. Please make sure you have entered some data.','failure'); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |