Using Yii2 in the View...
Products::find()->asArray()->all()
returns all products as array.
I'm looking for a way to make it return all products WHERE id != 1
I want to have only one place do modify what "->all()" returns for every model.
I know that Product::find()->where('id != 1')->...
is possible, but I don't want to write and maintain it in more than one place.
1) You can simply override
find()
method in your model:Usage:
2) Use scope.
Create custom query class:
Override
find()
method in your model:Then you can use it like this:
I think using second method is more flexible, because it makes code more clear.
Additional notes:
Hardcoded
id
is not good practice. Better replace it with equivalent condition.For this examples I used different way of specifying condition. See different ways of specifying condition in
where
statement in official documentation.