How to set default criteria for all search operations for model?

activerecord, criteria, php, yii

Solution

Use `CActiveRecord::defaultScope()` method as follows:

class Service extends CActiveRecord
{
    ...
    public function defaultScope(){
        return array(
            'order'=>'pos ASC'
        );
    }
    ...
}

This will be added for all find methods on the model. Read on scopes and defaultScopes for more information

Problem

I have a model: ``` class Service extends CActiveRecord { public static function model($className = __CLASS__) { return parent::model($className); } public static function getMainPageItems() { return self::model()->findAll(array( 'condition' => 'on_main = 1', 'order' => 'pos ASC' )); public static function getNonMainPageItems() { return self::model()->findAll(array( 'condition' => 'on_main = 0', 'order' => 'pos ASC' )); } ``` I want to set the model's default order to `pos ASC`. How can I set the model's default order?

Original source