我有一个包含部门的数据库表.我有另一张包含人的桌子.正如您所期望的那样,某个部门包含许多人,并且某个人在一个部门中.
当我想要将新人保留到数据库时,我创建一个Person对象并尝试将其Department属性设置为由Entity Manager管理的现有 Department对象.但是,当我试图坚持我的新人时,我得到一个例外:
通过关系'Entities\Person#department'找到了一个新实体,该关系未配置为级联实体的持久操作:Entities\Department @ 0000000016abe202000000000d29dd37.要解决此问题:在此未知实体上显式调用EntityManager#persist()或在映射中配置级联持久保存此关联,例如@ManyToOne(..,cascade = {"persist"}).
我并不完全理解异常部分,该部门称该部门是一个"未知实体",因为我是通过实体经理提取的.
如异常所示,我在yml metadata(cascade: ["persist"])中插入了一个级联.我的人然后得到了保存,但我最终在部门表中有了一个重复的部门,并带有一个新的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
Run Code Online (Sandbox Code Playgroud)
码:
$department = $em->getRepository('Department')->findOneBy(array('name' => $departmentName);
$person = new Person();
$person->setName('Joe Bloggs');
$person->setDepartment($department);
$em->persist($person);
$em->flush();
Run Code Online (Sandbox Code Playgroud)