如何仅序列化 child 的 ID

How can I serialize only the ID of a child

我正在寻找序列化 object 的 child 的正确方法。 我有以下 类:

class company {
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @Groups ({"get"})
     */
    private $id;
}

class User {
    /**
     * @ORM\Column(type="string", length=180, unique=true)
     * @Groups ({"get"})
     */
    private $email;

    /**
     * @ORM\ManyToOne(targetEntity=Company::class, inversedBy="users")
     * @ORM\JoinColumn(nullable=false)
     * @Groups ({"get"})
     */
    private $company;
}

只要我在用户 object 上使用序列化程序,我就会收到以下响应。

{
    "id": 1,
    "email": "email@mydomain.com",
    "company": {
        "id": 1
    }
}

但我更喜欢下面的回复,我怎样才能得到这些?

{
    "id": 1,
    "email": "email@mydomain.com",
    "company": 1
}

您可以创建一个自定义规范化器,并在用户中汇总公司 - 因为它在 json 编码之前从原始对象(带有子实体)转换为数组。

symfony console make:serializer:normalizer [optional name, eg: 'UserNormalizer']

这将创建一个新的 class,部分内容为:

     public function normalize($object, $format = null, array $context = []): array
     {
         // $object is a User entity at this point
         $data = $this->normalizer->normalize($object, $format, $context);

         // Here: add, edit, or delete some data
         // and we summarise the company entity to just the ID.
         $data['company'] = $object->getCompany()->getId();

         return $data;
     }

当我用一个稍微复杂一点的实体来回溯原始实体(如果公司有一个回溯给用户的引用)时,它做了 'A circular reference',所以我在@Ignore 添加了一个注释用户实体中的字段,用于序列化目的。它仍然被提供给规范器,从传递给 normalize().

的对象中使用

您也可以序列化方法的结果:

class User {
    /**
     * @ORM\Column(type="string", length=180, unique=true)
     * @Groups ({"get"})
     */
    private $email;

    /**
     * @ORM\ManyToOne(targetEntity=Company::class, inversedBy="users")
     * @ORM\JoinColumn(nullable=false)
     */
    private $company;

    /**
     * @Groups ({"get"})
     */
    public function getCompanyId()
    {
        return $this->company->getId();
    }
}