Symfony2 Doctrine2 反序列化和合并实体问题

Symfony2 Doctrine2 De-Serialize and Merge Entity issue

我正在尝试将 json 反序列化为一个实体,然后合并该实体。

我相信我过去曾使用过此功能,我会发送 ID 和我希望更新的任何字段。例如:

在我的数据库中:

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

然后我将反序列化以下内容json并合并实体

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

预期结果为:

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

但是我得到以下信息:

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

就像我说的那样,我相信我在某个时候有这个工作,我不确定这是否与 jms_serializerem->merge 有关。

$customer->getFirst() returns null 实体合并前后

您以错误的方式使用了 Doctrine 合并。它所做的不是合并的字典定义。来自学说文档:

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

您可能应该逐个更新 $customer 的值。

反序列化器将您的 JSON 字符串转换为一个对象,仅此而已。它将使用您序列化的属性。如果未设置 属性,它将保持为空(或在 class 中指定的默认值)。

merge 方法还将 null 属性保存到数据库。

为避免这种情况,请查看以下答案:how to update symfony2/doctrine entity from a @Groups inclusion policy JMSSerializer deserialized entity

持久化实体后,在实体上调用 EntityManager::refresh() 方法应该加载缺少的属性。

还有相关的:

  • How to update a Doctrine Entity from a serialized JSON?
  • How to manage deserialized entities with entity manager?
  • Doctrine2 ORM Ignore relations in Merge

不是很优雅,但我认为这可以完成工作。

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