How to manage deserialized entities with entity manager?

后端 未结 2 1247
感情败类
感情败类 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

    0 讨论(0)
  • 2020-12-16 09:38

    I know this question is three years old, but it mislead me to think the only answer was using the merge operation. I'd like to add my two cents:

    The JMSSerializerBundle includes an object constructor for Doctrine entities. When you enable this constructor, the deserialized entities are managed entities that can be persisted(with $em->persist($entity)).

    Please check this comment to understand other benefits from this. And here is how you can enable it.

    0 讨论(0)
提交回复
热议问题