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]);
You can simply override find() method in your model:
public static function find()
{
return parent::find()->where(['storeActive' => 1]);
}