简体   繁体   English

Doctrine2应自动合并关联的实体

[英]Doctrine2 should automatically merge associated entities

I am building an order process, in which an Order object is built through many steps. 我正在构建一个订单流程,其中Order对象是通过许多步骤构建的。 After each step I put the partly finished Order object into the session , and in the final step I save it into the database. 在每个步骤之后,我将部分完成的Order对象放入session ,并在最后一步中将其保存到数据库中。

During the steps I load other, (already existing) associated objects into my Order object(eg. DiscountCoupon ). 在这些步骤中,我将其他(已经存在的)关联对象加载到我的Order对象中(例如, DiscountCoupon )。 The problem is that when I save my Order to the session and then load it in the next step, all associated entities will be detached. 问题是当我将Order保存到session然后在下一步中加载时,所有关联的实体都将被分离。 So when I want to save it to the database, the EntityManager throws an exception, which asks for setting a cascade=persist on the relationship. 因此,当我想将其保存到数据库时, EntityManager会抛出一个异常,要求在关系上设置cascade=persist

Of course, I dont need to persist those objects(they are already in the database). 当然,我不需要持久保存那些对象(它们已经存在于数据库中)。 The obvious solution could be to change those associated objects to merged ones(using EntityManager#merge method), however, I have a rather complicated object structure with multiple levels of embedded entities, so doing the above process would be rather inconvinient. 显而易见的解决方案可能是将那些关联对象更改为合并对象(使用EntityManager#merge方法),但是,我有一个相当复杂的对象结构,具有多级嵌入实体,因此执行上述过程将相当不方便。

Cannot Doctrine automatically do this task for me? 不能Doctrine自动为我做这个任务吗? So instead of 'complaining' about my detached entities, it could automatically merge them. 因此,不是“抱怨”我的分离实体,它可以自动合并它们。

As far as I can tell, you'd be creating some serious magic if you tried to make it entirely automatic. 据我所知,如果你试图让它完全自动化,你就会创造出一些严肃的魔力。

Your best bet is probably to implement a function with a signature like: mergeOrderEntities($Order, $EntityManager) which knows how to talk the Order structure and invoke EntityManager::merge() on all detached associated entities. 你最好的选择可能是实现一个带有签名的函数:mergeOrderEntities($ Order,$ EntityManager),它知道如何讨论Order结构并在所有分离的关联实体上调用EntityManager :: merge()。

As to why doctrine doesn't do this automatically, I'm not sure. 至于为什么学说不能自动完成,我不确定。 I suspect there are use cases where auto-merging of entities could be dangerous, or at least undesirable. 我怀疑在某些情况下,实体的自动合并可能是危险的,或者至少是不合需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM