Add Where-Clause to every DB-Query

Hey there,

I wanna use soft deletion in my application, which means i’ve added an attribute ‘deleted’ to every model. When i destroy a record, it doesn’t get really destroyed but this attribute is set to 1.

Now, i don’t want to have to use the Where-Clause ’ [font=“Lucida Console”]… AND deleted = 0[/font] ’ in every statement (respectively having to add it to every DBCriteria) i have in my whole application.

So my question is, is it somehow possible to add this clause automatically to every query i have in my application, maybe somewhere inside the core before the statement is executed? Or just tell the framework in another way, i only want to get records from the DB where ’ [font=“Lucida Console”]deleted = 0[/font] ’

You can set a defaultScope() - http://www.yiiframework.com/doc/api/1.1/CActiveRecord#defaultScope-detail

create a Base Model and define a custom scope in your base model something like following


class BaseActiveRecord extends CActiveRecord

{

    public function scopes()

    {

        return array(

            'valid'=>array(

                'condition'=>'deleted=0',

            )

        );

    }

}

then in your model inherit from that BaseActiveRecord and you can do the following


$model = Model::model()->valid()->findAll(); // returns array 

Worked. Thanks a lot!

you are welcome