Mark Johnson
Mark Johnson

Reputation: 645

yii2 add where condition model for every find

In Yii2 I am trying to change an ActiveRecord model so that every time the application runs a find(), or findAll() it will also add an extra where to the condition.

For example, the application calls find() method on the Stock model:

$UsersStockFound = Stock::Find()
->where(['stockActive' => 1]);

So, here is what I want to happen, I would like the model to add an extra condition before the users gets to see the results. Let's just pretend I have the tenant ref already stored under $this->tenant So I want to add this to the above query, but seamlessly through the model.

->AddWhere(['tenantId' => $this->tenantId]);

So in other words the whole will be as if it was:

$UsersStockFound = Stock::Find()
->where(['stockActive' => 1]);
->AddWhere(['tenantId' => $this->tenant]);

Upvotes: 1

Views: 3180

Answers (2)

BEJGAM SHIVA PRASAD
BEJGAM SHIVA PRASAD

Reputation: 2241

None of above solutions worked for me.. if you are having 'where` usage, whatever overrides you do, find will not work..

I found my own solution as below which will overwrite all ORM calls.

class model extends \yii\db\ActiveRecord
{

    public static function find()
    {
              
        return new CustomActiveRecordQuery(get_called_class());
    }

}
class CustomActiveRecordQuery extends ActiveQuery
{
    // ...
        public function prepare($builder)
    {
            $this->andWhere(['status' => 'Active']);
            return parent::prepare($builder);
    }
}

Upvotes: 1

Insane Skull
Insane Skull

Reputation: 9368

You can simply override find() method in your model:

public static function find()
{
    return parent::find()->where(['storeActive' => 1]);
}

Reference

Upvotes: 2

Related Questions