how to update symfony2/doctrine entity from a @Groups inclusion policy JMSSerializer deserialized entity

后端 未结 3 1230
清酒与你
清酒与你 2020-12-09 05:35

I\'m trying to update symfony2/doctrine entities using JMSSerializer with an @ExclusionPolicy:None @Groups Inclusion Policy.

 * @Serializer\\ExclusionPolicy(         


        
3条回答
  •  温柔的废话
    2020-12-09 06:15

    I found the answer.

    $serializer is a service created by the symfony2 integration bundle JMSSerializerBundle.

    The default service is jms_serializer.serializer initializes the JMSSerializer with the default Object Constructor UnserializeObjectConstructor and for doctrine I needed to deserialize with the DoctrineObjectConstructor.

    because I only use JMSSerializer in the project for serialize/deserialize of doctrine entities, I overwrote JMSSerializerBundle's jms_serializer.object_constructor with the alias of the proper object constructor service.

    
    

    Is there a better way to configure what object constructor the serializer uses?

    I also added the proper context to deserialize:

    $serializer->deserialize($jsonFoo,'Foo','json', DeserializationContext::create()->setGroups(array('flag')));
    
    result:
    Foo (id:1, name:'bar', flagged:true ,created_by:123)
    

    Using the doctrine object constructor, it figures out that I want to find the object and only apply updates to fields provided in $jsonFoo (and the flag group). This totally eliminates the need for doctrines entity manager merge and I can just persist the object properly.

    $em->persist($foo);
    $em->flush();
    

提交回复
热议问题