听起来code
本质上是一个用户名字段。如果code
未定义为数据库中的主键,最好不要将primaryKey
Model 属性设置为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;
}
}