Symfony – @ uniqueconstraint and @ column (unique = true) options differ at the doctrine ORM level
At the database level, there is no difference in defining uniqueness with one option instead of another, as shown below Although @ uniqueconstraint reads in its document that "it only makes sense in the context of schematool schema generation", is there an ORM level difference between them? I mean, when we run a query, do we deal with different things
> @UniqueConstraint > @Column(unique = true)
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",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;
Solution
Basically no difference Both create unique keys on columns
But @ uniqueconstraint has more possibilities With @ uniqueconstraint, you can specify a name for the key or span multiple columns The disadvantage is that more input (not worse), and the column name must be the column name in the database, not the PHP attribute name
@Unique = true on column is the easiest way to create a unique key on a single column
There is no difference when running a query ORM does not care about unique definitions In particular, at insert time, you get crashes about uniqueness violations from the database, not from orm You must ensure uniqueness yourself, for example, using unique entity authentication in symfony