Doctrine and composite unique keys Doctrine and composite unique keys mysql mysql

Doctrine and composite unique keys


Answer the question:

use Doctrine\ORM\Mapping\UniqueConstraint;/** * Common\Model\Entity\VideoSettings * * @Table(name="video_settings",  *    uniqueConstraints={ *        @UniqueConstraint(name="video_unique",  *            columns={"video_dimension", "video_bitrate"}) *    } * ) * @Entity */

See @UniqueConstraint


I find it more verbose to use only ORM and then prefix ORM in annotations. Also note that you can break annotation to several lines to make it more readable especially if you have several items to mention (index in the example below).

use Doctrine\ORM\Mapping as ORM;/** * VideoSettings * * @ORM\Cache(usage="NONSTRICT_READ_WRITE") * @ORM\Entity(repositoryClass="AppBundle\Repository\VideoSettingsRepository") * @ORM\Table(name="emails", uniqueConstraints={ *      @ORM\UniqueConstraint(name="dimension_bitrate", columns={"video_dimension", "video_bitrate"}) * }, indexes={ *      @ORM\Index(name="name", columns={"name"}) * }) */class VideoSettings


I know this is an old question, but I came across it while looking for a way to create composite PK and thought it could use some update.

Things are actually much simpler if what you need is a Composite Primary Key. (Which, of course, guarantees uniqueness) Doctrine documentation contains some nice examples by this url: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/composite-primary-keys.html

So the original example could look something like this:

/** * @var string $videoDimension * * @ORM\Id @ORM\Column(type="string") */private $videoDimension;/** * @var string $videoBitrate * * @ORM\Id @ORM\Column(type="string") */private $videoBitrate;

A few notes here:

  1. Column "name" is omitted since Doctrine is able to guess it based onthe property name
  2. Since videoDimension and videoBitrate are both parts of the PK - there is no need to specify nullable = false
  3. If required - the Composite PK may be composed of foreign keys, so feel free to add some relational mappings