[英]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? 那么最好的选择是什么?
Add a setId()
method, but that's probably a bad idea and undermines the doctrine default behaviour. 添加一个
setId()
方法,但这可能不是一个好主意,并且会破坏该学说的默认行为。
Use a custom Normalizer
that uses reflection to construct the object by just accessing the field. 使用自定义
Normalizer
,该Normalizer
仅通过访问字段即可使用反射来构造对象。
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中建立了一些东西吗?
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.