【问题标题】:How to set default criteria for all search operations for model?如何为模型的所有搜索操作设置默认条件?
【发布时间】:2012-12-16 05:57:19
【问题描述】:

我有一个模型:

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

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

【问题讨论】:

    标签: php activerecord yii criteria


    【解决方案1】:

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

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

    这将为模型上的所有查找方法添加。阅读scopesdefaultScopes了解更多信息

    【讨论】:

      【解决方案2】:

      解决此问题的一种方法是向名为 $order 的父类添加一个私有成员。

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

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

      【讨论】:

      • 谢谢,我知道这种方式。但是此时框架的可能性呢?
      • 啊,我的错(不太熟悉)
      猜你喜欢
      • 1970-01-01
      • 2019-03-07
      • 2013-09-16
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 2013-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多