【问题标题】:Symfony Serializer cannot handle Doctrine Id on deserializeSymfony 序列化器无法在反序列化时处理 Doctrine Id
【发布时间】:2017-04-11 09:24:55
【问题描述】:

我正在尝试在 Symfony 3 中序列化然后反序列化一个 Doctrine 实体。当然,它不适用于 id 属性,因为默认情况下 id 没有公共访问器。那么最好的选择是什么?

  1. 添加一个setId() 方法,但这可能是个坏主意 破坏了学说的默认行为。

  2. 使用自定义Normalizer,它使用反射来构造 只需访问该字段即可。

  3. 为实体提供一些自定义toArray()fromArray() 功能,并在序列化中使用数组值而不是对象。

或者我错过了什么? symfony 中是否已经为该用例内置了一些东西?

【问题讨论】:

    标签: php symfony serialization


    【解决方案1】:

    您可以使用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

    【讨论】:

      猜你喜欢
      • 2020-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      相关资源
      最近更新 更多