Prettyscripts

Yii: Accessing value in select as column

When selecting a column as alias name, a variable (property) of the same name must be manually defined in the model.

eg, SQL:

select sum(column_1) as alias_1 from table_1 group by id;

In the model file:

class MyModel as CActiveRecord {
    public $alias_1;
 
    function getAliasValue() {
        $criteria = new CDbCriteria();
        $criteria->select = array('sum(column_1) as alias_1');
        $criteria->group = 'id';
        $result = MyModel::model()->find($criteria);
        return $result->alias_1;
    }
}

Notes:

  • Line 2: define a new variable name.
  • Line 6: The name must be the same as the alias name used in select as clause.

4 comments

Leave a Reply