selectAs in CDbCriteria


$criteria->selectAs=array(

       'fullname' => "CONCAT(firstname,' ',lastname)",

    

       // for use with GROUP_BY:

       'postCount' => "COUNT(posts.post_id)",

    );

    

CDbCriteria::selectAs will be merged into the CDbCritereria::select. Makes sense? :)

It is non-trivial to track reserved alias names in criteria::select, so this might cause a headache while debugging if two or more columns will be returned with the same name accidentally.

But, this could happen with select, too. I like the idea. :)

for a simple Full name of a model I just add a function to the model itself.

public function getFullName()

{





    return $this->LastName.', '.$this->FirstName;


}

$model->Fullname would then be what you wanted. Just not from the database.

Sure. This was just an example. Using AS in SELECT helps in many situations that can’t be solved by adding a function to the model. E.g. when sorting by the AS column.

for sorting options you are right, haven’t thought of that from your example ;)

Adds some flexibility, so can’t be a bad thing.

Just for the record: As it’s nicer to have the AS columns defined in the AR i now “misuse” the defaultScope(). Did only a quick test but it looks promising. That way you should be able to add complex expressions too:


public $blabla;


public function defaultScope() {

    return array(

        'select'=>'*,IF( <some_condition_here>, column1, column2) AS blabla',

    );

}



You can use array to represent ‘select’

Thanks, Qiang.

Only problem i have now is when using "with()". If defined like this in an AR


public $blabla;


public function defaultScope() {

    return array(

        'select'=>array('*','CONCAT("demo",login) as blabla'),

    );

}



and then calling a ->with(…)->find(…), it throws an error about unknown column "*".

Any way to solve that?

Top of call stack:


#0 /usr/share/php/yii-1.0.11/db/ar/CActiveFinder.php(1164): CJoinElement->getColumnSelect(Array)

#1 /usr/share/php/yii-1.0.11/db/ar/CActiveFinder.php(401): CJoinQuery->__construct(Object(CJoinElement), Object(CDbCriteria))

#2 /usr/share/php/yii-1.0.11/db/ar/CActiveFinder.php(85): CJoinElement->find(Object(CDbCriteria))

#3 /usr/share/php/yii-1.0.11/db/ar/CActiveFinder.php(113): CActiveFinder->query(Object(CDbCriteria), true)