如何在yii中对数据库中的两个值求和

时间:2015-03-26 09:42:16

标签: php yii

我是yii的新手。我创建了一个包含amount和totalamount的表单。我已经在数据库中存储了totalamount = 1000.如果我给它应该添加totalamount的数量值并将其存储在database.i上,只需尝试这个,但该值不存储在数据库中。

public function actiontransaction()
{
    $model = new Transactionform;
    if(isset($_POST['submit'])) 
    {

        $model->username=$_POST['username'];
        $model->description=$_POST['description'];
        $model->amount=$_POST['amount'];    

        $model = Transactionform::model()->findByPK(27);
        echo $model-> totalamount+$model->amount=$_POST['amount'];
        $model->transactiondate=$_POST['transactiondate'];  

        if($model->validate())
        {
            if(!$model->save()) // save it here!
            {
                // do stuff after successful save
            }
        }

    }
    $this->render('bankreg',array('model'=>$model));
}

3 个答案:

答案 0 :(得分:0)

试试这个:

    ...
    $amount=$_POST['amount'];    //new amount
    $model = Transactionform::model()->findByPK(27);
    $model->totalamount = $model->totalamount + $amount; // total = previous + new
    ...

答案 1 :(得分:0)

由于您未将其正确分配给型号,因此未保存该值 了解$ _POST中的内容会很有用(希望它包含您尝试修改的对象的ID,因此您可以在调用findByPk时使用它来从数据库中检索数据)。
我尝试编辑你的代码:



public function actionTransaction()
{
    $model = new Transactionform;
    if(isset($_POST['submit'])) 
    {  
        $model = Transactionform::model()->findByPK($_POST['id']);
        $model->username = $_POST['username'];
        $model->description = $_POST['description'];
        $model->amount = $_POST['amount'];	
        $model->totalamount = $model->totalamount + $_POST['amount'];
        $model->transactiondate = $_POST['transactiondate'];	
			
        if($model->validate())
        {
            if(!$model->save()) // save it here!
            {
               // do stuff after successful save
            }
        }
    }
   	    $this->render('bankreg',array('model'=>$model));
}




答案 2 :(得分:0)

最后我通过这种方法得到答案。



 $model1=$model->findall();
          foreach($model1 as $model_amount)
		     $total_amount=$model_amount['totalamount'];
			 $amount=$_POST['amount'];   
		if($model->description=='D')	 
        	$model->totalamount = $total_amount + $amount;