加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – Doctrine 2坚持在ManyToOne关系中保持已经管理的实体

发布时间:2020-12-13 13:37:20 所属栏目:PHP教程 来源:网络整理
导读:我有一个包含部门的数据库表.我有另一个包含人的表.正如您所期望的那样,某个部门包含许多人,并且某个人在一个部门中. 当我想将新人保留到数据库时,我创建一个Person对象并尝试将其Department属性设置为由Entity Manager管理的现有Department对象.但是,当我尝
我有一个包含部门的数据库表.我有另一个包含人的表.正如您所期望的那样,某个部门包含许多人,并且某个人在一个部门中.

当我想将新人保留到数据库时,我创建一个Person对象并尝试将其Department属性设置为由Entity Manager管理的现有Department对象.但是,当我尝试坚持我的新Person时,我得到一个例外:

A new entity was found through the relationship
‘EntitiesPerson#department’ that was not configured to cascade
persist operations for entity:
EntitiesDepartment@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.

这必须是一个非常常见的用例.我在下面提供了我的代码和元数据.我应该做些什么改变?

元数据:

EntitiesPerson
  type: entity
  table: people
  fields:
    ...
    departmentId:
      type: integer
      unsigned: false
      nullable: false
      column: department_id
    ...
  manyToOne:
    department:
      targetEntity: EntitiesDepartment
      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();
问题是由使用实体管理器的不同实例首先获取部门,然后持久保存Person.

我的实体管理器现在是一个单例,所以无论哪个类请求实体管理器获取相同的实例.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读