我有下面的设置
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);我怎么才能解决这个问题?
发布于 2019-02-11 13:18:12
您可以尝试使用@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;https://stackoverflow.com/questions/54624986
复制相似问题