Using Activerecord find() method with db column alias'

I am new obviously. I am having trouble accessing an activerecord instance’s column’s value when using an alias for that column’s name. The code should hopefully make this more obvious:




$criteria = new CDbCriteria;

$criteria->select = 'MAX(votes) AS upvotes, MIN(votes) AS downvotes';        


$post = Post::model()->find($criteria);


echo $post->upvotes // CException Property "Post.upvotes" is not defined.



Am I missing something? With CodeIgniter’s Activerecord one can just rename the property by renaming the column with an alias, or using “AS” as in “SELECT oldname AS newname”. In the above select statement I think you can probably see why I want to rename column names. How can I access their retrieved results after using find()?

1 Like

You should define the attributes in your class before they can be used in ActiveRecord:


class Post extends CActiveRecord

{

     public $upvotes;

     public $downvotes;


...


}

Thank you.

You saved my day also for Yii2 with it!