Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 273
Shawn Northrop Avatar asked Jan 26 '15 04:01

Shawn Northrop


2 Answers

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 :

  • How to update a Doctrine Entity from a serialized JSON?
  • How to manage deserialized entities with entity manager?
  • Doctrine2 ORM Ignore relations in Merge
like image 186
slaur4 Avatar answered Oct 29 '22 18:10

slaur4


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.

like image 27
Udan Avatar answered Oct 29 '22 18:10

Udan