21

How to set uniqueness for multiple fields in ActiveRecord (Yii2)? I have tried as written in manual

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

But it doesn't work.

almost_done
  • 397
  • 2
  • 4
  • 15

3 Answers3

36

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']]
void
  • 718
  • 7
  • 21
  • 6
    targetAttribute works for me.. attribute generates error. – beginner Oct 06 '15 at 00:32
  • 3
    I feel something could not be right over here. Docs says `$attributes` *Attributes to be validated by this validator*. And `$targetAttribute` *The name of the ActiveRecord attribute that should be used to validate the uniqueness* **of the current attribute value.** So, `$targetAttribute` should works fine (in fact, it is working fine for me). Even own Yii2 docs examples use `targetAttribute` ever. – sdlins Dec 11 '16 at 17:10
6

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']]
Dhruv
  • 612
  • 7
  • 15
Kuldeep Dangi
  • 4,126
  • 5
  • 33
  • 56
  • Good clarification, although `comboNotUnique` was deprecated in 2.0.10 and will be removed altogether in 2.1. `message` should be used going forward. ([reference](http://www.yiiframework.com/doc-2.0/yii-validators-uniquevalidator.html#$comboNotUnique-detail)) – smsalisbury Oct 06 '17 at 21:15
1

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.

Ali MasudianPour
  • 14,329
  • 3
  • 60
  • 62