Hi all,
Please, could you give me some guidelines to make a query that SUMs all the values of a column, but has a related table in the WHERE clause?
I have this in my model:
class Gasto {
// ....
public $userName; // public property for the CGridView filter
public function attributeLabels()
{ // included to illustrate the problem
return array(
'id' => 'ID', // Id of the model
'value' => 'Value', // value I want to SUM
'userId' => 'User', // foreign key, not shown
'userName' => 'User', // not in this table
);
}
public function relations()
{
return array(
'Usuario' => array(self::BELONGS_TO, 'User', 'userId'),
);
}
private function getSearchCriteria(){
$criteria=new CDbCriteria;
$criteria->with = array('Usuario');
$criteria->compare('id',$this->id);
$criteria->compare('user.username', $this->userName, true);
return $criteria;
}
public function search() // this works
{
return new CActiveDataProvider($this, array(
'criteria'=>$this->getSearchCriteria(),
// ... order and pagination stuff
));
}
public function getSum()
{
$criteria = $this->getSearchCriteria();
$count = Gasto::model()->count($criteria); // < this works too
$criteria->select='SUM(value)'; // << this line wasnt here when I first posted this, but it was in my code.
// But Here is the problem:
$total = $this->commandBuilder->createFindCommand($this->getTableSchema(), $criteria)->queryScalar();
return $total;
}
}
Model Gasto is related with the User by its column userId.
I have the filter working in the CGridView, event the Gasto::model()->count($criteria) works, (it returns the count of the filtered items).
But commandBuilder seems to ignore the "with" property of the criteria.
I am trying with the join properties of the CDBCommand, but I am not geting anything better than this MySQL Error:
1054 Unknown column 'user.username' in 'where clause'. The SQL statement executed was: SELECT SUM(value) FROM `res_gastos` `t` WHERE user.username LIKE .....
As you can see, there is no JOIN in the query.
Thank you in advance and sorry if my english is not correct