yii2唯一验证器仅当字段不为空时

问题描述 投票:5回答:3

在Yii2中,我的数据库中有两个字段:emailshopId

  • EmailshopId应该是unique在一起
  • Email也可以是emptyNULL),而shopId总是一个整数

这些是我在模型中的规则:

[['email'],'default','value' => NULL],
[['shopId'], 'integer'],
[['email','shopId'], 'unique', 'targetAttribute' => ['email', 'shopId'], 'message' => 'Already taken!'],

如果我有两个条目,例如,这不起作用email="NULL"shopId="1"

我怎么解决这个问题?

php yii2
3个回答
2
投票

skipOnEmpty属性设置为false http://www.yiiframework.com/doc-2.0/yii-validators-validator.html# $ skipOnEmpty-detail


2
投票

虽然您的解决方案正在运行,但技术上并不正确。验证规则

[['email','shopId'], 'unique', 'targetAttribute' => ['email', 'shopId']]

如果email不为空(期望的功能),将验证shopId与给定的email是唯一的,但如果shopId不为空(不需要的话),它还将验证email对于给定的shopId是唯一的。您正在验证带有两个DB查询的两个字段。

符合您需求的验证规则是

[['email'], 'unique', 'targetAttribute' => ['email', 'shopId']]

说“如果email不是空的,检查emailshopId的组合是否唯一,并将结果绑定到email属性”。


0
投票

我在规则中使用了when条件

[
    ['email', 'shopId'],
    'unique',
    'targetAttribute' => ['email', 'shopId'],
    'message' => 'Diese E-Mail Adresse ist bereits registriert!',
    'when' => function ($model) {
        return !empty($model->email);
    }
],
© www.soinside.com 2019 - 2024. All rights reserved.