0

我有一个奇怪的问题。我的员工表有id ->int(11) 作为主键。它还有代码->varchar(36)、密码和其他一些字段。此代码和密码是员工用于登录系统的两个字段。我使用 cakePHP 表单助手构建带有 Code 字段和 Password 字段的登录页面;事情进展顺利。

今天,当我尝试使用 $this->Model->save 更新员工表的另一个字段时,它插入了一个新行而不是更新。那是我了解到我需要将代码设置为主键的时候。所以我放入$primaryKey = 'code'了我的 Employee 模型。

我输入的那一刻,我的登录页面中的代码字段消失了,只留下密码字段。当我删除 时$primaryKey = 'code',代码字段又回来了。

所以它与将代码设置为模型中的主键有关。有什么解决办法吗?

我需要能够使用代码更新员工行并在登录页面中保留我的代码字段。

4

1 回答 1

0

听起来code本质上是一个用户名字段。如果code未定义为数据库中的主键,最好不要将primaryKeyModel 属性设置为code.

我想大多数人会建议使用主键字段id来告诉 Cake 要更新哪个员工记录。但是,如果您必须使用code,请尝试以下操作:

假设您的code字段在数据库中具有唯一约束或使用 Cake 验证进行唯一验证,您可以使用它code来查找要更新的记录。一旦您拥有该记录($current在以下情况下),您就可以获得主键id,这是必需的,因此Model::save知道要更新哪个记录。

public function edit($code = null) {
    $current = $this->Employee->find('first', array(
        'conditions' => array(
            'Employee.code' => $code
        )
    ));
    $this->Employee->id = $current['Employee']['id'];

    if (!$this->Employee->exists()) {
        throw new NotFoundException(__('Invalid employee'));
    }
    if ($this->request->is('post') || $this->request->is('put')) {
        if ($this->Employee->save($this->request->data)) {
            $this->Session->setFlash(__('The employee has been saved'));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The employee could not be saved. Please, try again.'));
        }
    } else {
        $this->request->data = $current;
    }
}
于 2012-07-28T15:41:36.520 回答