为什么需要在ORM中分离和合并实体? [英] Why there is the need of detaching and merging entities in a ORM?

查看:141
本文介绍了为什么需要在ORM中分离和合并实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是关于Doctirne,但我认为可以扩展到许多ORM。

The question is about Doctirne but I think that can be extended to many ORM's.

分离:


实体与EntityManager分离,因此不再通过调用code> EntityManager#detach($ entity)方法来管理
或者通过
将分离操作级联到它。拆分的
实体(如果有的话)(包括删除该实体)所做的更改将不会在实体脱离后与数据库同步

An entity is detached from an EntityManager and thus no longer managed by invoking the EntityManager#detach($entity) method on it or by cascading the detach operation to it. Changes made to the detached entity, if any (including removal of the entity), will not be synchronized to the database after the entity has been detached.

合并:


合并实体是指(通常是分离的)实体的合并
进入EntityManager的上下文,以便它们再次被管理
。要将实体的状态合并到EntityManager中,请使用
EntityManager#merge($ entity)方法。通过的实体
的状态将被合并到该实体的托管副本,并且此副本将
随后返回。

Merging entities refers to the merging of (usually detached) entities into the context of an EntityManager so that they become managed again. To merge the state of an entity into an EntityManager use the EntityManager#merge($entity) method. The state of the passed entity will be merged into a managed copy of this entity and this copy will subsequently be returned.

我明白(几乎)这是如何工作的,但问题是:为什么需要分离/合并内容?你可以给我一个例子/方案,这两个操作可以使用/需要?

I understand (almost) how this works, but the question is: why one would need detaching/merging entitiies? Can you give me an example/scenario when these two operations can be used/needed?

推荐答案

一个实体?

当处理多个EM并避免并发冲突时,从EM(EntityManager)中分离实体被广泛使用,例如:

When should I Detaching an entity?
Detaching an entity from the an EM (EntityManager) is widely used when you deal with more than one EM and avoid concurrency conflicts, for example:

$user= $em->find('models\User', 1);
$user->setName('Foo');

// You can not remove this user, 
// because it still attached to the first Entity Manager
$em2->remove($user);
$em2->flush();

您无法控制 $ user 对象由 $ em2 ,因为它的会话属于 $ em ,最初加载 $ user 从数据库。他们如何解决上述问题?您需要分离对象:

You can not take control of $user object by $em2 because its session belongs to $em that initially load the $user from database. Them how to solve the problem above? You need to detaching the object:

$user= $em->find('models\User', 1);
$user->setName('Foo');

$em2->detach($user);
$em2->remove($user);
$em2->flush();

什么时候应该使用合并功能?

基本上当你想更新一个实体:

When should I use merging function?
Basically when you want to update an entity:

$user= $em->find('models\User', 1);
$user->setName('Foo');

$em->merge($user);
$em->flush();  

EM将比较数据库中的$用户和内存中的$ user。一旦EM识别更改的字段,它只会更新它们并保留旧的。

The EM will make a compare between the $user in database vs the $user in memory. Once the EM recognize the changed fields, it only updates them and keeps the old ones.

flush 方法触发提交,用户名将在数据库

The flush method triggers a commit and the user name will updated in the database

这篇关于为什么需要在ORM中分离和合并实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆