In database level, there is no difference when using one over another option for defining UNIQUENESS as shown below. Although @UniqueConstraint
reads in its documentation "It only has meaning in the SchemaTool schema generation context", is there a ORM level difference in between? I mean when we run queries, do things get handled differently?
EXAMPLE - @UniqueConstraint
CLASS
/**
* @ORM\Entity
* @ORM\Table(
* name="user",
* uniqueConstraints={
* @ORM\UniqueConstraint(columns={"email"})
* }
* )
*/
class User
{
/**
* @ORM\Column(name="email", type="string", length=100)
*/
private $email;
}
DQL
CREATE TABLE `user` (
`email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
UNIQUE KEY `UNIQ_8D93D649E7927C74` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
EXAMPLE - @Column - unique=true
CLASS
/**
* @ORM\Entity
* @ORM\Table(name="user")
*/
class User
{
/**
* @ORM\Column(name="email", type="string", length=100, unique=true)
*/
private $email;
}
DQL
CREATE TABLE `user` (
`email` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
UNIQUE KEY `UNIQ_8D93D649E7927C74` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
There is basically no difference. Both create a unique key on a column.
But @UniqueConstraint
has much more possibilities. With @UniqueConstraint
you can give the key a name or span over multiple columns. The downside is much more to type (not as worse) and the column names must be the column names in the database, not the php property name.
unique=true
on the @Column
is the simplest way of creating unique keys on a single column.
While running queries, there is no difference. The ORM doesn't care about unique definitions. Especially on inserts you get a crash from the database about uniqueness violation and not from the ORM. You have to ensure the uniqueness on your own, for example with the unique entity validation in Symfony.
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