Ruslan Bes
Ruslan Bes

Reputation: 2735

Default Criteria For Active Record

I have a following question about the best practice for ActiveRecord usage.

My case: I have a User model which is a normal CActiveRecord. In many cases I want to have lists of "active" users, defined in the database by WHERE condition "is_active = 1". Besides I want functions find(), findByAttributes(), findByPk() etc. to return the result only if the user is active (for example in "Password request" scenario).

I can always apply this WHERE condition explicitly before using find() functions but I'm searching a way to implement it with less code.

I came to the idea of creating a child class called UserActive and change its constructor like this:

function __construct($scenario='insert') {
    parent::__construct($scenario);

    $criteria = new CDbCriteria();
    $criteria->condition = "is_active = 1";
    $this->setDbCriteria($criteria);
}

But I'm not sure if this is a good practice to do this (Since CActiveRecord's constructor asks "Do NOT override the constructor unless it is absolutely necessary!"). Can anyone give advices for this situation?

Upvotes: 0

Views: 87

Answers (2)

Carlos Rodriguez
Carlos Rodriguez

Reputation: 169

Try this in your model.

public function defaultScope() {
    return array(
               'condition'=>'is_active = 1',
            );

}

Or define other scope Yii - using relations with scopes defined in the relation

Upvotes: 5

chris---
chris---

Reputation: 1546

That's right, you should never override __construct(). You can use model scopes for that. See http://www.yiiframework.com/doc/guide/1.1/en/database.ar#named-scopes

Upvotes: 1

Related Questions