Kenny Yap
Kenny Yap

Reputation: 1337

Yii-Active Record return average result of a specific column as a string

I have a quick question. How do I use the MySQL AVG() query with Yii active record model and pass is as a string? This is how I query with my code now but it return to me as a NULL array...

/**
 * Gets topic average rating by comments
 * @param int $topic_id the topic unique id
 *
 * @return int rate
 */
public static function WS_countAverageRating($topic_id){
    return ExploreComment::model()->findAll(array('select'=>"AVG(rating)",'condition'=>"topic_id='".$topic_id."'"));
}

Upvotes: 0

Views: 1349

Answers (1)

Alfred_P
Alfred_P

Reputation: 792

I think the most elegant way is to do it with a statistical relationship. Add something like this to your relations inside the model:

'avarageRating' => array(SELF::STAT, 'ExploreComment', 'topic_id', 'select' => 'AVG(rating)'),

Read more about statistical relations here: http://www.yiiframework.com/doc/guide/1.1/en/database.arr#statistical-query

Upvotes: 2

Related Questions