Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 unique validator only when field not empty

Tags:

php

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?

like image 456
kasoft Avatar asked Jun 06 '17 17:06

kasoft


1 Answers

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".

like image 105
MrBlc Avatar answered Oct 19 '22 04:10

MrBlc