2012-07-29 86 views
5

我知道我可以使用$this->Model->save()更新特定的記錄,如果我通過身份證,但我怎麼能更新該行上的單個字段?我有一個usersbalance字段。我想根據已有的內容更新balance字段。更新查詢與CakePHP

例如,用戶在餘額字段中有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電話嗎?

回答

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); 
    } 
3
$this->Model->saveField('balance','balance+1'); 

應該訣竅!

+0

打我:)這裏的API鏈接http://api.cakephp.org/class/model#method-ModelsaveField – tigrang 2012-07-29 02:44:17

+0

我甚至不是CakePHP的人(更多的是CodeIgniter的人),我想通了!抱歉! – David 2012-07-29 02:45:01

+4

只需要額外的注意:確保在撥打電話前設置了$ this-> Model-> id' – tigrang 2012-07-29 02:45:47

8

這應該這樣做:

$this->User->updateAll(array('User.balance' =>'User.balance + 1'), array('User.id' => $id));