How to use column aliases in AR ?

I was trying some code (with blog demo):

$criteria = new CDbCriteria(array('select'=>array('id','title')));

echo Post::model()->find($criteria)->title;

Here is everything OK

$criteria = new CDbCriteria(array('select'=>array('id','title as xxx')));

echo Post::model()->find($criteria)->title;

This returns nothing

$criteria = new CDbCriteria(array('select'=>array('id','title as xxx')));

echo Post::model()->find($criteria)->xxx;

This returns [tt]CException - Property "" is not defined.[/tt]

$criteria = new CDbCriteria(array('select'=>array('id','title as xxx')));

echo Post::model()->find($criteria)->getAttribute('xxx');

This returns [tt]CDbException - Post does not have attribute "xxx".[/tt]

Is there any way to access xxx?

In doc about RAR there is written that we can use select with relations:


select: a list of columns to be selected for the related AR class. It defaults to '*', meaning all columns. Column names should be disambiguated using aliasToken if they appear in an exp​ression (e.g. COUNT(??.name) AS nameCount).

But how to access nameCount ??

Declare a public member xxx.

Thank you, it works.

but …

This code works …

$criteria = new CDbCriteria(array('select' => 'CONCAT_WS(" - ", column1, column2) as description'));

echo table1::model()->find($criteria)->description;

But this doesn't:

in table1 relations

'relation' => array (self::BELONGS_TO, 'table2', 'fk', 'select' => 'CONCAT_WS(" - " ,??.column1, ??.column2) as description'),

and both lines:

echo table1::model()->find()->relation->description;

echo table1::model()->with('relation')->find()->relation->description;

Throws [tt]CDbException - Active record "table2" is trying to select an invalid column "CONCAT_WS(" - "". Note, the column must exist in the table or be an exp​ression with alias.[/tt]

I was trying it with mysql database.

Am I doing something wrong or there is no possibility to select that expresion neither with lazy nor eager loading?

Please use an array to represent the selected columns (this is undocumented). If you use a string, Yii will attempt to split it into columns according to comma, which gives incorrect result in your case.

Thanks again. It's working.