Yii2 model::find()具有默认where条件
在视图中使用Yii2Yii2 model::find()具有默认where条件,yii2,Yii2,在视图中使用Yii2 Products::find()->asArray()->all() 以数组形式返回所有产品。 我正在寻找一种方法,使其返回id!=1. 我只想让一个地方修改“->all()”为每个模型返回的内容。 我知道Product::find()->where('id!=1')->…是可能的,但我不想在多个地方编写和维护它。1)您可以简单地覆盖模型中的find()方法: /** * @return \yii\db\ActiveQuery */ public stat
Products::find()->asArray()->all()
以数组形式返回所有产品。
我正在寻找一种方法,使其返回id!=1.
我只想让一个地方修改“->all()”为每个模型返回的内容。
我知道Product::find()->where('id!=1')->…
是可能的,但我不想在多个地方编写和维护它。1)您可以简单地覆盖模型中的find()
方法:
/**
* @return \yii\db\ActiveQuery
*/
public static function find()
{
return parent::find()->where(['<>', 'id', 1]);
}
namespace app\models;
use yii\db\ActiveRecord;
class Product extends ActiveRecord
{
/**
* @inheritdoc
* @return ProductQuery
*/
public static function find()
{
return new ProductQuery(get_called_class());
}
}
2)使用
创建自定义查询类:
namespace app\models;
use yii\db\ActiveQuery;
class ProductQuery extends ActiveQuery
{
public function withoutFirst()
{
$this->andWhere(['<>', 'id', 1]);
return $this;
}
}
然后你可以这样使用它:
$products = Products::find()->withoutFirst()->all();
我认为使用第二种方法更灵活,因为它使代码更清晰
补充说明:
- 硬编码
不是好的做法。最好用等效条件替换它id
- 对于这个例子,我使用了不同的方法来指定条件。请参阅中的
语句中指定条件的不同方法where
where()
,例如Product::find()->where(['col'=>$value])->all()
将覆盖模型中的“默认”where()
。除了在第二个示例中使用scope类之外,还有其他解决方法吗?@JamesG已经定义了where()
,您需要使用和where()
/或where()
,以保持初始条件。
$products = Products::find()->withoutFirst()->all();