Yii关系STAT与多列

时间:2017-08-22 05:52:48

标签: php yii

我试图从Review表中获取STAT关系。这是我的代码

public function relations()
    {
        return array(
            'avarageRating' => array(SELF::STAT, 'Reviews', array('make_code'=>'make_code', 'model_code'=>'model_code', 'year'=>'year'), 'select' => 'AVG(overall_rating)'),
    }

表格看起来像这样

make_code | model_code | year | overall_rating
01        | 02         | 2015 | 4.2
01        | 03         | 2014 | 4.0
01        | 02         | 2015 | 3.0

我想获得具有相同overall_ratingmake_codemodel_code

的所有行的year平均值

示例,make_code 01,model_code 02和2015年。(4.2+3.0 / 2)$model->avarageRating应该给我 3.6

现在,当我使用$model->avarageRating;调用关系时,我收到错误

preg_match() expects parameter 2 to be string, array given

知道我做错了什么?

已编辑:

function getavarageRating() {
        $criteria = new CDbCriteria();
        $criteria->select='ROUND(AVG(overall_rating), 1) AS avg, COUNT(overall_rating) AS total';
        $criteria->addCondition("make_code=:make_code");
        $criteria->addCondition("model_code=:model_code");
        $criteria->addCondition("year=:year");
        $criteria->params = array(':make_code' => $this->make_code, ':model_code' => $this->model_code, ':year' => $this->year);


        $query = Reviews::model()->find($criteria);

        return $query;
    }

我在我的模型中添加了这个功能,这就是workws。但我有办法使用关系吗?

1 个答案:

答案 0 :(得分:0)

似乎你得到了你的结果的集合,所以你应该通过索引访问,尝试访问第一个元素

 $model[0]->avarageRating;