Symfony UniqueEntity vs UniqueConstraint vs unique=true

Viewed 3928

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?

2 Answers

@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.

Related