Symfony的循环关系问题参考

问题描述 投票:0回答:1

我有以下设置

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

我怎样才能解决这个问题?

php symfony4 circular-reference
1个回答
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;
© www.soinside.com 2019 - 2024. All rights reserved.