2012-07-29 15 views
5

Wiem, że mogę użyć $this->Model->save(), aby zaktualizować konkretny rekord, jeśli przekazuję identyfikator, ale jak mogę zaktualizować pojedyncze pole w tym wierszu?Zapytanie UPDATE z CakePHP

Mam tabelę users z polem balance. Chcę zaktualizować pole balance na podstawie tego, co już tam jest.

Na przykład użytkownik w polu salda ma 20 USD. Chcę dodać 1 USD, aby zarobić 21 USD. Jedynym sposobem, wiem, jak to zrobić jest użycie

$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) 
)); 

Jak mogę dostać, że wszystkie do jednego save połączenie?

Odpowiedz

1

spróbuj tego: -

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'); 

Powinien załatwić sprawę!

+0

Bijcie mnie :) Oto Link API http://api.cakephp.org/class/model#method-ModelsaveField – tigrang

+0

Nie jestem nawet facetem CakePHP (bardziej z facetem CodeIgniter) i odkryłem to! Przepraszam! – David

+4

Tylko dodatkowa uwaga: upewnij się, że '$ this-> Model-> id' jest ustawione przed wywołaniem – tigrang

8

ten powinien zrobić:

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