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.
The Yii documentation summarizes this concisely: An Active Record class is associated with a database table, an Active Record instance corresponds to a row of that table, and an attribute of an Active Record instance represents the value of a particular column in that row.
Yii2 has a bunch of built in validators see. From Yii2 docs. In your rules array, add the unique validator to email and username like so: You are trying to validate the model before any attributes have been assigned. Update your controller code to the following:
Class yiidbActiveRecord. ActiveRecord is the base class for classes representing relational data in terms of objects. Active Record implements the Active Record design pattern. The premise behind Active Record is that an individual yiidbActiveRecord object is associated with a specific row in a database table.
Returns a value indicating whether the given active record is the same as the current one. The comparison is made by comparing the table names and the primary key values of the two active records. If one of the records is new they are also considered not equal. Whether the two active records refer to the same row in the same database table.
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']]
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']]
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