#4153·orm

DDC-3354: 使用 indexBy 关联替换索引项时,无法满足唯一性约束

作者: doctrinebot创建于 2014年10月17日更新于 2026年9月30日
标签Bug

Jira issue originally created by user cblegare: Using a bidirectional one-to-many relation having an 'indexBy' clause on the owning side and a unique constraint over the indexed field and the 'mappedBy' field of the inverse side, replaced indexed fields being inserted before removed violated the unique constraint. As stated in the code examples below, if done without the unique constraint, when replacing an indexed field, the row is replaced in the database (new one created, old one deleted). Here is an example: Person: type: entity id: id: type: integer generator: strategy: AUTO oneToMany: emailAddresses: targetEntity: Email indexBy: name mappedBy: owner cascade: [all] orphanRemoval: true Email: type: entity id: id: type: integer generator: strategy: AUTO fields: name: type: string nullable: false address: type: string nullable: false uniqueConstraints: unique*named_person*email: columns: [owner_id, name] manyToOne: owner: targetEntity: Person inversedBy: emailAddresses joinColumn: name: owner_id referencedColumnName: id class Person { protected $id; /** * @var Collection|Email[] $emailAddresses * * * * * I would expect this to work. * * * * * public function setEmailAddress_expected($name, $emailAddress) { * * * * * Expected to work but throws UniqueConstraintViolationException * * * * * If done without the 'unique*named_person*email' constraint', it * * * * * works properly creating a new Email and deleting the old one. * * * * * $this->emailAddresses->set( (string) $name, new Email($this, (string) $name, (string) $emailAddress) ); * * * * * * * * * * * I would expect this to work. * * * * * public function setEmailAddress*expected*too($name, $emailAddress) { * * * * * Expected to work but throws UniqueConstraintViolationException * * * * * If done without the 'unique*named_person*email' constraint, it * * * * * works properly creating a new Email and deleting the old one. * * * * * $this->emailAddresses->remove((string) $name); * * * * * $this->emailAddresses->set( (string) $name, new Email($this, (string) $name, (string) $emailAddress) ); * * * * * * * * * * * Works * * * * * public function setEmailAddress_works($name, $emailAddress) { * * * * * $existing = $this->emailAddresses->get((string) $name); * * * * * if ($existing) { * * * * * $existing->setAddress((string) $emailAddress); * * * * * } else { * * * * * $this->emailAddresses->set( (string) $name, new Email($this, (string) $name, (string) $emailAddress) ); * * * * * } * * * * * }