我有一个包含部门的数据库表.我有另一个包含人的表.正如您所期望的那样,某个部门包含许多人,并且某个人在一个部门中.
当我想将新人保留到数据库时,我创建一个Person对象并尝试将其Department属性设置为由Entity Manager管理的现有Department对象.但是,当我尝试坚持我的新Person时,我得到一个例外:
A new entity was found through the relationship
‘Entities\Person#department’ that was not configured to cascade
persist operations for entity:
Entities\Department@0000000016abe202000000000d29dd37. To solve this
issue: Either explicitly call EntityManager#persist() on this unknown
entity or configure cascade persist this association in the mapping
for example @ManyToOne(..,cascade={“persist”}).
我并不完全理解异常部分,该部门称该部门是一个“未知实体”,因为我是通过实体经理提取的.
如异常所示,我在yml元数据中插入了一个级联(cascade:[“persist”]).我的人然后得到了保存,但我最终在department表中有了一个重复的部门,并带有一个新的id.
这必须是一个非常常见的用例.我在下面提供了我的代码和元数据.我应该做些什么改变?
元数据:
Entities\Person type: entity table: people fields: ... departmentId: type: integer unsigned: false nullable: false column: department_id ... manyToOne: department: targetEntity: Entities\Department joinColumn: department_id referenceColumnName: id
码:
$department = $em->getRepository('Department')->findOneBy(array('name' => $departmentName); $person = new Person(); $person->setName('Joe Bloggs'); $person->setDepartment($department); $em->persist($person); $em->flush();