Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/228.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在Symfony序列化程序中序列化实体关系manytone?_Php_Symfony - Fatal编程技术网

Php 如何在Symfony序列化程序中序列化实体关系manytone?

Php 如何在Symfony序列化程序中序列化实体关系manytone?,php,symfony,Php,Symfony,例如,我有一个关系用户→Posts和我想使用Symfony序列化组件获取Post中用户的id: /** * @var User * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="posts") * @Groups({"public"}) */ private $user; 如何为具有用户id的Post实体获取JSON { ... "user_id": 123, ... } 但也能够序列化用户。根

例如,我有一个关系用户→Posts和我想使用Symfony序列化组件获取Post中用户的id:

/**
 * @var User
 * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="posts")
 * @Groups({"public"})
 */
private $user;
如何为具有用户id的Post实体获取JSON

{
   ...
   "user_id": 123,
   ...
}

但也能够序列化用户。

根据文档,您可以使用处理序列化深度来避免实体关系上的循环引用异常。 ()


所以类似这样的方法会奏效:

/**
 * @return int|null
 * @Groups({"public"})
 */
public function getUserId(): ?int
{
    return $this->getUser()->getId();
}

安东·梅德韦杰夫为什么只为了获取json而需要使用序列化程序?您可以尝试实体转换器,它们可能非常适合您的需要,因为我正在构建JSONAPI,而不是表单。
$result = $serializer->normalize($level1, null, array('enable_max_depth' => true));
/*
$result = array(
    'foo' => 'level1',
    'child' => array(
            'foo' => 'level2',
            'child' => array(
                    'child' => null,
                ),
        ),
);
*/
/**
 * @return int|null
 * @Groups({"public"})
 */
public function getUserId(): ?int
{
    return $this->getUser()->getId();
}