我知道如果我传入id,我可以使用$this->Model->save()
来更新特定记录,但是如何更新该行上的单个字段?
我有一个users
表,其中包含balance
字段。我想根据已存在的内容更新balance
字段。
例如,用户在余额字段中有20美元。我想加1美元使其成为21美元。我知道如何做到这一点的唯一方法是使用
$balance = $this->Model->find('first', array(
'conditions' => array('User.id' => $userId),
'fields' => array('User.balance')
));
$this->Model->save(array(
'User' => array('id' => $userId, 'balance' => $balance['User']['balance'] + $credit)
));
如何将所有内容整合到一个save
来电?
答案 0 :(得分:8)
这应该做:
$this->User->updateAll(array('User.balance' =>'User.balance + 1'), array('User.id' => $id));
答案 1 :(得分:3)
$this->Model->saveField('balance','balance+1');
应该做的伎俩!
答案 2 :(得分:1)
试试这个: -
public function edit($id = null) {
$this->layout = 'admin_layout';
$this->Model->id = $id;
if (!$this->Model->exists()) {
throw new NotFoundException(__('Invalid model'));
}
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->Model->save($this->request->data)) {
$this->Session->setFlash(__('The model has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The model could not be saved. Please, try again.'));
}
} else {
$this->request->data = $this->Model->read(null, $id);
}
$datd = $this->Model->find('list');
$this->set('data', $datd);
}