Yii2 model :: find()默认情况下的条件

Tod*_*kov 11 yii2

在视图中使用Yii2 ...

Products::find()->asArray()->all()
Run Code Online (Sandbox Code Playgroud)

将所有产品作为数组返回.我正在寻找一种方法让它返回所有产品WHERE id!= 1我想只有一个地方做修改" - > all()"为每个模型返回.我知道这Product::find()->where('id != 1')->...是可能的,但我不想在不止一个地方编写和维护它.

aro*_*hev 23

1)您可以简单地覆盖find()模型中的方法:

/**
 * @return \yii\db\ActiveQuery
 */
public static function find()
{
    return parent::find()->where(['<>', 'id', 1]);
}
Run Code Online (Sandbox Code Playgroud)

用法:

$products = Products::find()->all();
Run Code Online (Sandbox Code Playgroud)

2)使用范围.

创建自定义查询类:

namespace app\models;

use yii\db\ActiveQuery;

class ProductQuery extends ActiveQuery
{
    public function withoutFirst()
    {
        $this->andWhere(['<>', 'id', 1]);

        return $this;
    }
}
Run Code Online (Sandbox Code Playgroud)

find()模型中的覆盖方法:

namespace app\models;

use yii\db\ActiveRecord;

class Product extends ActiveRecord
{
    /**
     * @inheritdoc
     * @return ProductQuery
     */
    public static function find()
    {
        return new ProductQuery(get_called_class());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它:

$products = Products::find()->withoutFirst()->all();
Run Code Online (Sandbox Code Playgroud)

我认为使用第二种方法更灵活,因为它使代码更清晰.

补充说明:

  • 硬编码id不是好习惯.更好地用等效条件替换它.

  • 对于这个例子,我使用了不同的指定条件的方法.请参阅官方文档中的where声明中指定条件的不同方法.

  • 在第一个例子中,在代码中的其他位置使用另一个`where()` - 例如`Product :: find() - > where(['col'=> $ value]) - > all();`将覆盖你的'默认的'`where()`在模型中.有没有办法解决这个问题,除了在第二个例子中使用范围类? (4认同)
  • @JamesG已经定义了“ where()”,您需要使用“ andWhere()”或“ orWhere()”来保持初始状态。 (2认同)