Saturday, March 19, 2022

[FIXED] Default scope in Yii 1.1

Issue

AR model Player:

public function scopes()
{
    return array(
        'proleague' => array(
            'condition' => 'mode = "proleague"',
        ),
        'main' => array(
            'condition' => 'mode = "main"',
        ),
    );
}

Using model Player:

Player::model()->
proleague()->
with('startposition')->
findAllByAttributes(... here some condition ...);

^^^ That's all ok. Scope-condition will be executed. But...


In my project I have many places where any scope for Player model doesn't specified and in this cases I need use this scope-condition as default:

        'main' => array(
            'condition' => 'mode = "main"',
        )

If I add defaultScope() method to Player model like this

public function defaultScope()
{
    return array(
        'condition' => 'mode = "main"',
    );
}

the next code

Player::model()->
proleague()->
with('startposition')->
findAllByAttributes(... here some condition ...);

won't run correct. I won't get mode = "proleague" condition, becouse I'll use defaultScope() with mode = "main".


Any suggestions? How can I resolve the problem?


Solution

You should just use the resetScope(true) method. It "removes" the defaultScope filter.

$model = Player::model()->resetScope(true)->proleague();


Answered By - Nikola

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.