Symfony循环关系参考问题

时间:2019-02-11 06:26:28

标签: php symfony4 circular-reference

我有以下设置

Entity/User
---------------
 /**
  * @ORM\ManyToMany(targetEntity="App\Entity\UserGroup", mappedBy="users")
  */
  private $userGroups;


Entity/UserGroup
    ---------------
 /**
  * @ORM\ManyToMany(targetEntity="App\Entity\User", inversedBy="userGroups")
  */
  private $users;

如您所见,我具有manyTomany双向关系,

  • 一个用户属于多个组
  • 一个网上论坛可以有多个用户

当我序列化关系(以便处理API请求)时,

我深深嵌套了json对象

$groups = $this->entityManager
     ->getRepository(UserGroup::class)
     ->findAll();
$normalizer = new ObjectNormalizer();
$normalizer->setCircularReferenceLimit(1);

$normalizer->setCircularReferenceHandler(function ($object) {
     return $object->getId();
});

$encoder = new JsonEncoder();
$serializer = new Serializer(array($normalizer), array($encoder));

$groups = $serializer->serialize($groups, 'json');
return View::create(json_decode($groups, true), Response::HTTP_OK);

output

我该如何解决?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用@Groups()批注根据上下文指定要序列化对象的哪些属性。

https://symfony.com/doc/current/components/serializer.html#attributes-groups

因此,当您序列化对象时,请传递带有组的数组

$groups = $serializer->serialize($groups, 'json', ['groups' => 'user_groups.index']);

然后在您的实体中,将该组添加到要包含的属性中

 Entity/UserGroup
 ---------------
 /**
  * @ORM\ManyToMany(targetEntity="App\Entity\User", inversedBy="userGroups")
  * @Groups({"user_groups.index"})
  */
  private $users;