简体   繁体   中英

Default scope in Yii 1.1

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?

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

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

create a new Class for this.

<?php   
## e.g. protected/models/
class MyCoreAR extends CActiveRecord
{
    /**
        * Switch off the default scope
        */
        private $_defaultScopeDisabled = false; // Flag - whether defaultScope is disabled or not


    public function setDefaultScopeDisabled($bool) 
        {
                $this->_defaultScopeDisabled = $bool;
        }

        public function getDefaultScopeDisabled() 
        {
                return $this->_defaultScopeDisabled;
        }

        public function noScope()
        {
        $obj = clone $this;               
        $obj->setDefaultScopeDisabled(true);

        return $obj;
        }

    // see http://www.yiiframework.com/wiki/462/yii-for-beginners-2/#hh16
    public function resetScope($bool = true)
    {
        $this->setDefaultScopeDisabled(true);
        return parent::resetScope($bool);
    }


    public function defaultScope()
    {
        if(!$this->getDefaultScopeDisabled()) {
         return array(
                 'condition' => 'mode = "main"',
            );
        } else {
            return array();
        }
    }
}

In your code:

// no default scope
$model = Player::model()->noScope()->proleague();

// with default scope
$model = Player::model()->proleague();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM