resetScope for defaultScope in relation

Hi,

I have found many threads on this, mostly from 2010, few from 2011:

http://www.yiiframework.com/search/?q=resetscope&lang=&type=

But it seems that nobody has solved the problem: if you have a defaultScope in a model class which is used in a relation, but in that relation you don’t want to use it, there’s no way to reset it. For instance, assume that you normally want to see only active posts in a blog, so you define inside the Posts class this defaultScope:


public function defaultScope()

{

   $alias = $this->getTableAlias(false, false);

   return array(

  	'condition'=>$alias.".active='1'"

   );

}

but then you need to see every post, active AND inactive, writen by a given user, and you establish a relation in User class:


public function relations()

{

   return array(

  	'allposts'=>array(self::BELONGS_TO, 'Posts', 'userId'),

   );

}

then if you use:

$criteria->with = array(

‘allposts’=>array(‘scopes’=>array(‘resetScope’)),

);

but this won’t reset the default scope. And this won’t work either:


public function relations()

{

   return array(

  	'allposts'=>array(self::BELONGS_TO, 'Posts', 'userId', 'scopes'=>array('resetScope')),

   );

}

So, this problem is a real pain in the a$$ (sorry, too many hours trying to figure out how to ignore the default scope :angry: ). Using no defaultScopes is not an option, at least for me at this point, because it implies modifying a ton of criterias which assume the defaultScope exist. So, what can be done? Any help will be appreciated.

Regards.

Update: it seems that adding resetScope as in User::model()->resetScope()->findAll($criteria) helps. Does this reset every scope, including those ones from the relations?

Because the real problem here is the misuse of default scope. If a scope needs to be enabled/disabled conditionally then it isn’t a default scope imho.

One possible workaround: Since you stated in your post that removing default scope is not an option, I would create a subclass of Post which is identical to the parent class with the exception of default scope - it should be empty. Then I would use the child class in relation definitions where default scope must be ignored.

IN my case is needed in just one case, to get logs of operations done by users, even deleted ones. Your solution seems to be good fot this case. Thanks.