Can anyone explain what's the conceptual difference between @UniqueEntity validator, @UniqueConstraint table annotation and unique=true option of @Column annotation.
I understand that @UniqueConstraint adds UNIQUE index on database level and @UniqueEntity validates on ORM level. So what option shall I use, or do I use all of them?
This required option is the field (or list of fields) on which this entity should be unique. For example, if you specified both the email and name field in a single UniqueEntity constraint, then it would enforce that the combination value is unique (e.g. two users could have the same email, as long as they don't have the same name also).
This is commonly used, for example, to prevent a new user to register using an email address that already exists in the system. If you want to validate that all the elements of the collection are unique use the Unique constraint. In order to use this constraint, you should have installed the symfony/doctrine-bridge with Composer.
@UniqueConstraint and unique=true are part of Doctrine and do similar thing. When you set unique=true on a particular column, then Doctrine will create a unique key on this column physically in database. @UniqueConstraint can be used to create a unique key in database on multiple columns (complex unique key).
If you need to require two fields to be individually unique (e.g. a unique email and a unique username ), you use two UniqueEntity entries, each with a single field. It defines the validation group or groups of this constraint.
@UniqueConstraint and unique=true are part of Doctrine and do similar thing.
When you set unique=true on a particular column, then Doctrine will create a unique key on this column physically in database.
@UniqueConstraint can be used to create a unique key in database on multiple columns (complex unique key). But if you pass a single column, then the result will be exactly the same as using unique=true on that field.
@UniqueEntity on the other hand is not a part of Doctrine, but it's a part of Symfony framework. While options above are used by Doctrine to generate proper schema, this one is just a validator used usually by Symfony Form Component at time of submitting the form.
So to answer your final question - yes, you usually should use both @UniqueEntity and one of @UniqueConstraint or unique=true.
As stated in documentation, @UniqueConstraint annotation is used for creation of unique constraint on multiple columns, when unique=true is used for unique constraint on one column.
UniqueEntityValidator exists to show friendly error message and unique database constraint's purpose is to make sure you don't store duplicate data.
So the answer to your question is like this - you should use both database constraint and @UniqueValidator.
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