如何为模型的所有搜索操作设置默认条件


How to set default criteria for all search operations for 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'
    ));
}

我想将模型的默认顺序设置为pos ASC

如何设置模型的默认顺序?

使用CActiveRecord::defaultScope()方法如下:

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

这将被添加到模型上的所有find方法中。更多信息请阅读作用域和defaultscope

一种方法是为父类添加一个名为$order的私有成员。

您需要为它创建getter和setter(以便您可以在需要时更改默认值)

然后只需在每个需要它的函数的'order'元素中调用$this->$order