CakePHP 2.x:如何在控制器中获取最后一个插入单个字段?

时间:2015-12-26 07:26:20

标签: cakephp orm cakephp-2.0 cakephp-2.x

我有一个tansaction表,并有一个名为balance的字段。在这里,我尝试使用新数据更新此字段,但在新事务中插入。所以我需要控制器中的平衡场。所以,我试过下面的代码。

$client_id = $this->request->data['Transaction']['user_id'];
$new = $this->Transaction->find('first', array(
    'conditions'=>array('Transaction.user_id'=> $client_id),
    'fields'=>array('Transaction.balance')
));

$this->request->data['Transaction']['balance'] =$this->request->data['Transaction']['debit_money']-$this->request->data['Transaction']['credit_money']+new;

但在这里,我没有得到旧的余额数据。

1 个答案:

答案 0 :(得分:1)

$new是一个关联数组。您正在为数字添加数组。

尝试以下方法:

$client_id = $this->request->data['Transaction']['user_id'];
$new = $this->Transaction->find('first', array(
    'conditions'=>array('Transaction.user_id'=> $client_id),
    'fields'=>array('Transaction.balance')
));

$this->request->data['Transaction']['balance'] = 
    $this->request->data['Transaction']['debit_money']
    - $this->request->data['Transaction']['credit_money']
    + $new['Transaction']['balance'];

或者,这也应该有效:

$client_id = $this->request->data['Transaction']['user_id'];

$this->request->data['Transaction']['balance'] = 
    $this->request->data['Transaction']['debit_money']
    - $this->request->data['Transaction']['credit_money']
    + $this->Transaction->field('balance',array('Transaction.user_id'=> $client_id),        
));