使用Doctrine时在多个表之间实施UNIQUE约束

时间:2019-03-28 11:49:38

标签: php mysql doctrine-orm

使用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>

0 个答案:

没有答案