2014-11-24 41 views
1

所以說我想只保存2與特定交易領域我的系統*基本上我從庫存股票」CakePHP的2.X:在saveField()使用變量

public function admin_take($id = null) { 
    if (!$this->Inventory->exists($id)) { 
     throw new NotFoundException(__('Invalid inventory item')); 
    } 
    if ($this->request->is(array('post', 'put'))) { 
     if ($this->request->data['Inventory']['amount_taken'] < $this->Inventory['Inventory']['amount']){ 
       amt = $this->request->data['Inventory']['amount_taken']; 
       $this->Inventory['Inventory']['amount'] = $this->Inventory['Inventory']['amount'] - amt; 
       $this->Inventory['Inventory']['amount_taken'] = $this->Inventory['Inventory']['amount_taken'] + amt; 
       $this->Inventory->saveField('amount_taken','x'); 
       $this->Inventory->saveField('amount','y'); 
       $this->Session->setFlash(__('The inventory item has been saved.')); 
       return $this->redirect(array('action' => 'index')); 
      } 
      else if ($this->request->data['Inventory']['amount_taken'] > $this->Inventory['Inventory']['amount']) { 
       $this->Session->setFlash(__('request could not be processed, not enough inventory stock to fulfil request .')); 
      } 
      else { 
       $this->Session->setFlash(__('The request could not be processed, please try again.')); 
      } 

     } 
    } 
    else { 
     $options = array('conditions' => array('Inventory.' . $this->Inventory->primaryKey => $id)); 
     $this->request->data = $this->Inventory->find('first', $options); 
    } 
} 

是取出物品有可能用包含上面算術運算中更改數據的變量替換saveField中的x和Y嗎?

大多數我看到的示例傾向於在saveField $ stringValue中使用實際字符串,如果我確實需要字符串?我會去用字符串替換這裏?

回答

1

答案形式戴夫確實是正確的只是改變一下看看。 Cakephp已經完成了很多數據庫操作,而且你的代碼也有很多。

$this->Inventory->saveField('amount_taken','x'); 
$this->Inventory->saveField('amount','y'); 

是2操作。更好的是:

$this->Inventory->save(array('amount_taken' =>'x', 'amount' => 'y')); 

$this->Inventory->set('amount_taken','x'); 
$this->Inventory->set('amount','y'); 
$this->Inventory->save(); 
+1

Dave的答案是正確的,但我挑這也爲要去回合專門只更新表中的字段了一把更有效的方式。謝謝先生 – 2014-11-28 17:45:24

0

是有可能替換x和Y與變量saveField 從上面的算術運算包含改變的數據?

它。試試吧,你會看到它的作品。

如何將我去與字符串替換嗎?

步驟1)用您的算術運算替換'x'或'y'。這可以通過使用「複製」和「粘貼」快捷鍵輕鬆完成。 (CTRL + C/Ctrl + P鍵在Windows上)

步驟2)慶祝!