简体   繁体   English

Symfony序列化程序无法在反序列化时处理Doctrine ID

[英]Symfony Serializer cannot handle Doctrine Id on deserialize

I am trying to serialize and then deserialize a Doctrine Entity in Symfony 3. Well it does not work for the id property of course because there's no public accessor to the id by default. 我正在尝试序列化然后在Symfony 3中反序列化一个Doctrine实体。好吧,它当然不适用于id属性,因为默认情况下没有对id的公共访问器。 So what's the best option for that? 那么最好的选择是什么?

  1. Add a setId() method, but that's probably a bad idea and undermines the doctrine default behaviour. 添加一个setId()方法,但这可能不是一个好主意,并且会破坏该学说的默认行为。

  2. Use a custom Normalizer that uses reflection to construct the object by just accessing the field. 使用自定义Normalizer ,该Normalizer仅通过访问字段即可使用反射来构造对象。

  3. Give the entity some custom toArray() , fromArray() functionality and use the array values instead of the object in the serialization. 给实体提供一些自定义的toArray()fromArray()功能,并在序列化中使用数组值而不是对象。

Or am i missing something? 还是我错过了什么? Is there already something build into symfony for that usecase? 该用例已经在symfony中建立了一些东西吗?

This might be what you're looking for? 可能是您在寻找什么? I've recently started looking into it. 我最近开始研究它。

You can use object_to_populate option to do that : 您可以使用object_to_populate选项执行此操作:

    // retrieve entity to update from DB
    $oldProduct = $this->getDoctrine()->getRepository(Product::class)->find($request->request->get('id'));

    $product = $this->get('serializer')->deserialize($request->getContent(), Product::class, 'json', array('object_to_populate' => $oldProduct));

    $entityManager = $this->getDoctrine()->getManager();
    $entityManager->persist($product);
    $entityManager->flush();

See Deserializing in an Existing Object documentation 请参阅现有对象文档中的反序列化

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM