Yii2 model::find() 使用默认 where 条件 [英] Yii2 model::find() with default where conditions
问题描述
在视图中使用 Yii2...
Using Yii2 in the View...
Products::find()->asArray()->all()
将所有产品作为数组返回.我正在寻找一种方法让它返回所有产品 WHERE id != 1我只想让一个地方修改->all()"为每个模型返回的内容.我知道 Product::find()->where('id != 1')->...
是可能的,但我不想编写和维护它不止一处.
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) 您可以简单地覆盖模型中的 find()
方法:
1) You can simply override find()
method in your model:
/**
* @return \yii\db\ActiveQuery
*/
public static function find()
{
return parent::find()->where(['<>', 'id', 1]);
}
用法:
$products = Products::find()->all();
2) 使用范围.
创建自定义查询类:
namespace app\models;
use yii\db\ActiveQuery;
class ProductQuery extends ActiveQuery
{
public function withoutFirst()
{
$this->andWhere(['<>', 'id', 1]);
return $this;
}
}
覆盖模型中的 find()
方法:
Override find()
method in your model:
namespace app\models;
use yii\db\ActiveRecord;
class Product extends ActiveRecord
{
/**
* @inheritdoc
* @return ProductQuery
*/
public static function find()
{
return new ProductQuery(get_called_class());
}
}
然后你可以这样使用它:
Then you can use it like this:
$products = Products::find()->withoutFirst()->all();
我认为使用第二种方法更灵活,因为它使代码更清晰.
I think using second method is more flexible, because it makes code more clear.
附加说明:
硬编码
id
不是好习惯.最好用等效条件替换它.
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.
这篇关于Yii2 model::find() 使用默认 where 条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!