我正在尝试编辑我的一个成员密码(用户已允许我)。
现在对于这个函数,我有以下操作:
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid USer'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The User has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The User could not be saved. Please, try again.'));
}
} else {
}
}
但是,当我尝试保存时,出现以下错误:
2013-10-21 11:53:53 Error: [PDOException] SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'MarcEmp' for key 'username'
因此,它尝试插入一个新条目。
有谁知道我做错了什么?
您忘记将当前 id 设置为更新,因此 Cake 将默认尝试创建新记录。尝试添加:
$this->User->id = $id;
就在保存操作之前。所以你的整个函数应该看起来像:
/**
* Edit an existing user.
*
* @param int $id The user id to edit.
*/
public function edit($id) {
if (!$this->User->exists($id)) {
throw new NotFoundException(__('Invalid User'));
}
if ($this->request->is('post') || $this->request->is('put')) {
$this->User->id = $id; // <-- Add it here
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The User has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The User could not be saved. Please, try again.'));
}
}
}