2014-11-24 44 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)庆祝!