Symfony2 Doctrine2 De-Serialize and Merge Entity issue

南笙酒味 提交于 2019-12-10 15:07:41

问题


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


回答1:


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



回答2:


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.




回答3:


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();
}


来源:https://stackoverflow.com/questions/28144842/symfony2-doctrine2-de-serialize-and-merge-entity-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!