How to set uniqueness for multiple fields in ActiveRecord (Yii2)?

targetAttribute will be used as of latest yii2 docs (2017)

['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]

In this case field 'a1' will receive error message.

And the another case:

[['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']]

Now 'a1' and 'a2' attributes will receive error message if 'a1' and 'a2' are not unique together.

for custom message comboNotUnique will be used instead of message

[['a1', 'a2'], 'comboNotUnique' => 'Package Id already exist.', 'unique', 'attribute' => ['a1', 'a2']]

From docs:

// a1 needs to be unique
['a1', 'unique']
// a1 needs to be unique, but column a2 will be used to check the uniqueness of the a1 value
['a1', 'unique', 'targetAttribute' => 'a2']
// a1 and a2 need to be unique together, and they both will receive error message
[['a1', 'a2'], 'unique', 'targetAttribute' => ['a1', 'a2']]
// a1 and a2 need to be unique together, only a1 will receive error message
['a1', 'unique', 'targetAttribute' => ['a1', 'a2']]
// a1 needs to be unique by checking the uniqueness of both a2 and a3 (using a1 value)
['a1', 'unique', 'targetAttribute' => ['a2', 'a1' => 'a3']]

You can write your unique fields like below:

[['field1','field2'], 'unique']

Now, both, field1 and field2 should be unique.

As of Yii2's official document:

targetAttribute: the name of the attribute in targetClass that should be used to validate the uniqueness of the input value. If not set, it will use the name of the attribute currently being validated. You may use an array to validate the uniqueness of multiple columns at the same time.

Tags:

Yii2