0

我正在尝试编辑我的一个成员密码(用户已允许我)。

现在对于此功能,我有以下操作:

        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'

所以它尝试插入一个新条目。

有谁知道我做错了什么?

4

1 回答 1

3

您忘记将当前 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.'));
        }
    }
}
于 2013-10-21T11:57:08.497 回答