使用Doctrine时,如何对两个不同表中的列强制实施UNIQUE约束?例如,EntityB.some_property
对于给定的EntityA.account_id
必须是唯一的吗?如果要在不使用Doctrine的情况下进行此操作,则只需在account_id
中复制entity_b
并添加约束。但是,对于Doctrine,这将在Account
中创建一个EntityB
对象,这是不希望的。
entity_a
- id (PK)
- account_id (FK references account.id)
entity_b
- id (PK)
- primary_table_id (FK references entity_a.id)
- some_property (must be unique for a given account_id)
如下所示,我当前的方法只是在EntityB中创建了一个我不希望拥有的Account实体。
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
<entity name="NS\App\Entity\EntityA" table="entity_a">
<id name="id" type="integer">
<generator strategy="IDENTITY"/>
</id>
<many-to-one field="account" target-entity="Account" fetch="LAZY">
<join-columns>
<join-column name="account_id" referenced-column-name="id" on-delete="CASCADE" nullable="false"/>
</join-columns>
</many-to-one>
</entity>
</doctrine-mapping>
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping https://www.doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
<entity name="NS\App\Entity\EntityB" table="entity_b">
<unique-constraints>
<unique-constraint name="uniqueSomeProperty" columns="some_property, account_id_constraint"/>
</unique-constraints>
<id name="id" type="integer">
<generator strategy="IDENTITY"/>
</id>
<field name="someProperty" type="integer" column="some_property"/>
<many-to-one field="accountConstraint" target-entity="Account" fetch="LAZY">
<join-columns>
<join-column name="account_id_constraint" referenced-column-name="id" on-delete="CASCADE" nullable="false"/>
</join-columns>
</many-to-one>
</entity>
</doctrine-mapping>