How to manage deserialized entities with entity manager?

后端 未结 2 1263
感情败类
感情败类 2020-12-16 08:38

I am using JMSSerializerBundle to serialize my entities to json and deserialize json into entities, but I think this question applies for any deserialization techniques.

2条回答
  •  悲&欢浪女
    2020-12-16 09:30

    You need to use the merge() method on the EntityManager as merging entities refers to the merging of entities into the context of an EntityManager so that they can become managed again. In order 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.

    $detachedEntity = unserialize($serializedEntity); 
    $entity = $em->merge($detachedEntity);
    

    Also be sure to note when you want to serialize/unserialize entities you have to make all entity properties protected, never private. The reason for this is, if you serialize a class that was a proxy instance before, the private variables won’t be serialized and a PHP Notice is thrown.

    More information can be found in the doctrine documentation here:

    http://doctrine-orm.readthedocs.org/en/2.0.x/reference/working-with-objects.html#merging-entities

提交回复
热议问题