【发布时间】: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);
我该如何解决这个问题?
【问题讨论】:
标签: php symfony4 circular-reference