In Yii2 I have two fields in my Database: email and shopId
Email and shopId should be unique togetherEmail could also be empty (NULL) while shopId is always an integerThese 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?
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With