Search code examples
jsonsymfonydoctrine-ormjms-serializer

Symfony2 Doctrine2 De-Serialize and Merge Entity issue


I am trying to de-serialize json into an Entity and then Merge the Entity.

I believe I had this working in the past where I would send the ID and any fields I wished to update. For example:

In my DB:

| id |  first  | last  |   city   |
|  1 |  Jimmy  | James | Seattle  |

I would then de-serialize the following json and merge the entity

$json = { "id" : 1, "city": "chicago"}
$customer = $serializer->deserialize($json, 'App\CustomerBundle\Entity\Customer', 'json');
$em->merge($customer);

the expected result would be:

| id |  first  | last  |   city   |
|  1 |  Jimmy  | James | Chicago  |

However I am getting the following:

| id |  first  | last  |   city   |
|  1 |  null   | null  | Chicago  |

Like I said I believe I had this working at some point, I am unsure if this is related to the jms_serializer or em->merge.

$customer->getFirst() returns null Before and After the entity is Merged


Solution

  • The deserializer transforms your JSON string into an object, nothing more. It will use the properties you serialized. If a property is not set, it will remain null (or the default value specified in your class).

    The merge method will also persist null properties to database.

    To avoid that, look at the answer from : how to update symfony2/doctrine entity from a @Groups inclusion policy JMSSerializer deserialized entity

    After you have persisted your entity, calling EntityManager::refresh() method on your entity should load missing properties.

    Also related :