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

In Yii2 I have two fields in my Database: email and shopId

  • Email and shopId should be unique together
  • Email could also be empty (NULL) while shopId is always an integer

These are my rules in the Model:

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

This is not working when I have two entries with e.g. email="NULL" and shopId="1".

How can I solve this?

Set skipOnEmpty property to false http://www.yiiframework.com/doc-2.0/yii-validators-validator.html#$skipOnEmpty-detail

I used the when condition inside the rule

[
    ['email', 'shopId'],
    'unique',
    'targetAttribute' => ['email', 'shopId'],
    'message' => 'Diese E-Mail Adresse ist bereits registriert!',
    'when' => function ($model) {
        return !empty($model->email);
    }
],

While your solution is working it isn't technically correct. Validation rule

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

will validate email to be unique with given shopId if email is not empty (desired functionality), but it will also validate shopId to be unique with given email if shopId is not empty (unwanted). You are validating two fields with two queries to DB.

Validation rule that fits your needs is

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

saying "If email is not empty, check if combination of email and shopId is unique and bind result to email attribute".