【问题标题】:yii detecting if scope is in useyii 检测范围是否在使用中
【发布时间】:2012-09-14 00:05:14
【问题描述】:

我想知道是否有一种方法可以检测 yii 中的 AR 搜索是否正在使用范围?

例如,一个模型可能包含 2 个作用域:

class MyModel extends CActiveRecord
{
    ...
    function myScope1()
    {
        $this->getDbCriteria()->mergeWith(array(
            'join'=>'etc...',
            'condition'=>'foo = bar',
        ));
        return $this;
    }

    function myScope2()
    {
        $this->getDbCriteria()->mergeWith(array(
            'join'=>'etc...',
            'condition'=>'foo2 = bar2',
        ));
        return $this;
    }
    ....
}

我这样称呼 AR:

$results = MyModel::model()->myScope1()->myScope2()->findAll();

这是一个非常动态的网站,有超过 2 个范围,有些使用,有些没有。如果正在使用另一个范围,则不应应用几个范围。为了避免数百个if else 声明,我可以这样做:

class MyModel extends CActiveRecord
{
    ...
    function myScope1()
    {
        $this->getDbCriteria()->mergeWith(array(
            'condition'=>'foo = bar',
        ));
        return $this;
    }

    function myScope2()
    {
        if($this->appliedScopes('myScope1')==false)
        {
            // scope myScope1 isn't applied, so apply this scope:
            $this->getDbCriteria()->mergeWith(array(
                'condition'=>'foo2 = bar2',
            ));
        }
        return $this;
    }
    ....
}

【问题讨论】:

    标签: yii scopes named-scopes


    【解决方案1】:

    典型的,几乎在发布后立即想一个解决方法!

    在我的情况下,在两个范围之间应用“或”将起作用,所以;

    class MyModel extends CActiveRecord
    {
        ...
        function myScope1()
        {
            $this->getDbCriteria()->mergeWith(array(
                'join'=>'etc...',
                'condition'=>'foo = bar',
            ));
            return $this;
        }
    
        function myScope2($useAnd=true)
        {
            $this->getDbCriteria()->mergeWith(array(
                'join'=>'etc...',
                'condition'=>'foo2 = bar2',
            ),$useAnd);
            return $this;
        }
        ....
    }
    

    这样调用:

    $results = MyModel::model()->myScope1()->myScope2(false)->findAll();
    

    【讨论】:

      猜你喜欢
      • 2012-06-04
      • 2017-02-28
      • 2012-11-11
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 2012-09-18
      • 1970-01-01
      相关资源
      最近更新 更多