yii2 add where condition to 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]);

Hi,

Try to change your "addWhere" into AndWhere.

Also remove the ; in the line above the "addWhere" …

It should look like this:




$UsersStockFound = Stock::find()

->where(['stockActive' => 1])

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

Regards

Read the following section of the guide. This is exactly what you want.

ActiveRecord - Customizing Query Classes

Sorry my VERY poort syntax distracted from the question.

I have had it answered here:

http://stackoverflow.com/questions/35892106/yii2-add-where-condition-model-for-every-find

But I have an additional issue now.

If have an override function in my model:


public static function find()

{

    return parent::find()->where(['storeActive' => 1]);

}

Let’s say I put the above code in a Stock model.

If I use


Stock::find()-all();

this seems to ignore the above where condition I added. so it returns all records not just the ones where ‘storeActive’ = 1

ok it’s not Stock::Find()->All() that was the issue, it was Stock::Find()->where(…some condition…)->All()

reason is that the ->where() was overwriting the andWhere I had in the find() override method.

So I changed it to Stock::Find()->andWhere(…some condition…)->All()

and it all works.

andWhere seems to default to where() if there is no where already. So as a rule i’ll use that from now on.