【问题标题】:Symfony Circular relation reference issueSymfony 循环关系参考问题
【发布时间】:2019-02-11 06:26:27
【问题描述】:

我有以下设置

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】:

    您可以尝试使用@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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 2014-02-01
      相关资源
      最近更新 更多