5
votes

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

3
What do you mean by "merge the entity" ? You want to update values in database or load missing properties into your object ?slaur4
I am trying to load an entity by deserializing json containing the entity id. I thought that it would load the missing properties ie: $serializer->deserialize("{"id":1, "city": "chicago"}, .....) would return a Entity with the properties ( id => 1, first => Jimmy, last => James, city => chicago) where city is overwritten but the rest of the data is loaded.Shawn Northrop

3 Answers

5
votes

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 :

1
votes

You are using Doctrine merge in the wrong way. What it does is not what the dictionary definition of merge is. From Doctrine docs:

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.

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

You probably should update the values of $customer one by one.

0
votes

Not extremely elegant, but I think this would get the job done.

$customer = $em->getRepository('CustomerBundle:Customer')
            ->findOneById($jsonParsedId);
if ($customer) {
    $customer->setCity($jsonParsedCity);
    $em->persist($customer);
    $em->flush();
}