我正在尝试序列化然后反序列化 Symfony 3 中的 Doctrine 实体。它不适用于 id
属性当然是因为没有公共(public)访问器 id
默认情况下。那么最好的选择是什么?
setId()
方法,但这可能是个坏主意破坏了学说的默认行为。
Normalizer
使用反射来构造对象,只需访问该字段。
toArray()
, fromArray()
功能并在序列化中使用数组值而不是对象。 或者我错过了什么? symfony 中是否已经为该用例构建了一些东西?
最佳答案
您可以使用 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();
见 Deserializing in an Existing Object documentation
关于php - Symfony Serializer 无法在反序列化时处理 Doctrine Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43341843/