Using @ Embedded / @ Embeddable with Doctrine 2.5 and Unique Constraints

Doctrine 2.5 allows @Embeddable and @Embedded annotations - gives developers the ability to create objects together with Value objects. If you use a composer, from May 2014 you need: "minimum-stability": "dev" in your composer.json to use it.

I have a Server object, and I'm trying to map an IpAddress value IpAddress to this. @Embeddable and @Embedded work fine here.

However, I want the Server object to have a unique constraint on the IpAddress property that maps to the value object. This will work for the regular property, but for the built-in, I get an exception when trying to update my schema from my objects:

Doctrine SchemaException - @Embeddable @Embedded

Server entity

 namespace App\Model\Entity; use App\Model\Entity\ValueObjects\Server\IpAddress, Doctrine\ORM\Mapping as ORM; /** * Class Server * * @ORM\Table(name="servers", uniqueConstraints={@ORM\UniqueConstraint(name="unique_ip_address", columns={"ipAddress"})}) * @ORM\Entity(repositoryClass="App\Model\Repository\ServerRepository") */ class Server { /** * @var IpAddress * * @ORM\Embedded(class="App\Model\Entity\ValueObjects\Server\IpAddress") */ private $ipAddress; } 

Value IpAddress Object

 namespace App\Model\Entity\ValueObjects\Server; use Doctrine\ORM\Mapping as ORM; /** * Class IpAddress * * @package App\Model\Entity\ValueObjects\Server * * @ORM\Embeddable */ class IpAddress { /** * @var string * * @ORM\Column(name="ip_address", type="string", length=15, nullable=false) */ private $ipAddress; } 

I suppose I'm matching classes correctly. How to place a unique constraint on an inline object? I tried the syntax . in defining the column section uniqueConstraints , but this was a complete assumption and, of course, failed.

+6
source share
1 answer

Jimbo edit: Basically, the answer to this is to remove UniqueConstraints from the Server object and put it directly directly into the value object's property.

Based on the output of your schema, the column name in the index should be ipAddress_ip_address

@ORM \ Table (name = "servers", uniqueConstraints = {@ORM \ UniqueConstraint (name = "unique_ip_address", columns = {" ipAddress_ip_address "})})

Alternatively, if the IP address is unique in all the tables built into it, you can put the restriction in the IpAddress class.

 /** * @var string * * @ORM\Column(name="ip_address", type="string", length=15, nullable=false, unique=true) */ private $ipAddress; 
+5
source

Source: https://habr.com/ru/post/969850/


All Articles