jaime
jaime

Reputation: 57

sum criteria select/condition in yii

It doesn't say what error it is but it doesn't display properly. I think it's trying to display an array but I thought the criteria is summing the stars, no?

    $criteria = new CDbCriteria;
    $prod_id = Yii::app()->request->getQuery('id');
    $count = Review::model()->countByAttributes(array('target_product_id'=>$prod_id));
    $criteria->select = 'sum(star) AS sum';
    $criteria->condition = 'target_product_id = $prod_id';
    $total = $model->findAll($criteria);

Upvotes: 0

Views: 3702

Answers (3)

Hearaman
Hearaman

Reputation: 8726

Use queryScalar() to solve this very simply.

        echo Yii::app()->db->createCommand("SELECT SUM(star) FROM YourStarTable where target_product_id=$prod_id")->queryScalar();

OR

        $id=2;
        $command=Yii::app()->db->createCommand();
        $command->select('SUM(star) AS sum');
        $command->from('YourStarTable');
        $command->where('target_product_id=:id', array(':id'=>$id));
        echo $command->queryScalar();

Upvotes: 2

Let me see
Let me see

Reputation: 5094

try this
$criteria->condition = "target_product_id = $prod_id";
Either change the single quotes to double quotes

OR

$criteria->condition = 'target_product_id = :name';
$criteria->params=array(':name'=>$prod_id);

Upvotes: 0

Joe Miller
Joe Miller

Reputation: 3893

I think your problem might lie on this line

$criteria->condition = 'target_product_id = $prod_id';

It should read

$criteria->condition = 'target_product_id = ' . $prod_id;

Upvotes: 0

Related Questions