Temporarily Disabling Defaultscope

Hello, I need to be able to disable the defaultScope for one query. I have looked at all the API docs and all, I found resetScope(), which says that it removes all scopes, but that’s not true. I’m getting errors and in the errors it shows me the SQL Query Yii has made and I see the scopes are working. How do I disable scopes? Is this a bug? Do I need to upgrade to Yii 2.0 for resetScope() to work?




defaultScope() {


return array(

'valid' => 'is_valid=1'

);


}


someOtherFunction() {

SomeModel::model()->resetScope()->with($some_stuff)->findAllByAttributes($attributes);

}



1.) I think your defaultScope is wrong. I guess you ment "condition" => "is_valid=1", right?

2.) I think the problem is that scopes are applied as soon as a finder method is used (see CActiveRecord::query() https://github.com/yiisoft/yii/blob/1.1.13/framework/db/ar/CActiveRecord.php#L1290). This means that you are first removing the scopes via resetScope() but they are later applied again when calling findAllByAttributes(). A quick hack could be to add a scope that you call "includeInvalid" which simply overwrites the default scope with a "condition" => "is_valid=1 OR is_valid=0".

The query woud then be something like




someOtherFunction() {

    SomeModel::model()->includeInvalid()->with($some_stuff)->findAllByAttributes($attributes);

}



Yes that is what I meant, thank you for noticing. I will try that thanks.

EDIT: I tried to overwrite the scope, which didn’t work. When I looked at the SQL statement it created it did “(is_valid=0) AND (is_valid=1 OR is_valid=0)”. It didn’t overwrite the scope it just added to it. Unfortunately I wasn’t specific with my error. The error that I’m getting is that the “is_valid” column is ambiguous. I need to remove all references to the “is_valid” column. I apologize for not being specific with the question.

Dear Friend

I have a model Post.

The defaultScope in the model.




public function defaultScope()

	{

		return array(

		'order'=>"create_time DESC",

		);

	}



In a view I have the following code.




$criteria=Post::model()->getDbCriteria();

Post::model()->resetScope(true);

echo "Order without scopes."."</br>";

$posts=Post::model()->findAll();

foreach($posts as $post)

	echo date("Y/m/d H:i:s",$post->create_time)."</br>";

	

echo "</br>";


Post::model()->setDbCriteria($criteria);

echo "Order with scopes reapplied."."</br>";

$posts=Post::model()->findAll();

foreach($posts as $post)

	echo date("Y/m/d H:i:s",$post->create_time)."</br>";



3828

scopes.png

My inference is that we can remove the scopes and reapply the scopes on the fly.

Regards.