Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine ORM level difference between @UniqueConstraint and @Column(unique=true) options

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?

  • @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", 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;
like image 932
BentCoder Avatar asked Oct 18 '15 09:10

BentCoder


1 Answers

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.

like image 191
Emii Khaos Avatar answered Oct 11 '22 01:10

Emii Khaos