0

スコープが 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;
    }
    ....
}
4

1 に答える 1

0

通常、投稿直後に回避策を考えてください。

私の場合、2 つのスコープ間に「OR」を適用するとうまくいきます。

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-09-13T16:04:46.693 に答える