How to get the sum of column data in Yii using query?

I want the SUM of the data to be available in a specific column using a Yii query. Here is the code:

$resource_cnt = Resources::model()->findAll(array(
     'select'=>'prj_id, SUM(amount) as amt',
     'condition'=>'prj_id=:prj_id',
     'params'=>array(':prj_id'=>$_POST['Resources']['prj_id']))
);

      

I tried using the above query. But he didn't get the SUM of the variable amt

.

+3


source to share


2 answers


The "right" thing to do in Yii is, if you want it to work well in the model, declare a property in Resources

called amt

. Then it should work with your request. Yii only populates these attributes from a select query that it can find in the model.



class Resources.... {

  public $amt;
...

  public yourFunction() {

    $resource_cnt = Resources::model()->findAll(array(
      'select'=>'prj_id, SUM(amount) as amt',
      'condition'=>'prj_id=:prj_id',
      'params'=>array(':prj_id'=>$_POST['Resources']['prj_id']))
    );

    echo $resource_cnt->amt;
  }

...
}

      

+3


source


I changed the request using CreateCommand. Thanks to this, I got the sum of the selected column. Here is the request.



$resource_cnt = Yii::app()->db->createCommand()
->select('prj_id, sum(amount) as amt')
->from('resources')
->where('prj_id = ' . $_POST['Resources']['prj_id'])
->queryRow();

      

+2


source







All Articles