[英]Symfony Serializer: Deserialize with relation
I test the serializer component and try to do the following.我测试序列化程序组件并尝试执行以下操作。
I have an Article entity:我有一个文章实体:
class Article
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=50)
*/
private $title;
/**
* @ORM\Column(type="text")
*/
private $content;
/**
* @ORM\OneToMany(targetEntity=Comment::class, mappedBy="article", orphanRemoval=true, cascade={"persist"})
*/
private $comments;
//getter/setter...
and a Comment entity:和评论实体:
class Comment
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=50)
*/
private $title;
/**
* @ORM\Column(type="text")
*/
private $content;
/**
* @ORM\ManyToOne(targetEntity=Article::class, inversedBy="comments", cascade={ "persist" })
* @ORM\JoinColumn(nullable=false)
*/
private $article;
//getter/setter...
When a send a json to the controller:当发送 json 到 controller 时:
{
"title": "My comment",
"content": "This is a comment",
"article": {
"id": 1
}
}
1
exists1
的文章I would like the relationship with Article to be deserialized:我想反序列化与 Article 的关系:
#[Route('', name: "comment_create", methods: ['POST'])]
public function create(Request $request): JsonResponse
{
$comment = $this->serializer->deserialize($request->getContent(), Comment::class, 'json');
// $this->entityManager->persist($comment);
// $this->entityManager->flush();
return $this->json($comment, Response::HTTP_CREATED);
}
but the article is not linked.但文章没有链接。
{"id":null,"title":"My comment","content":"This is a comment","article":{"id":null,"title":null,"content":null,"comments":[]}}
Where is my mistake?我的错误在哪里? Can the symfony serializer do this?
symfony 序列化程序可以做到这一点吗?
Try to use following for deserialization:尝试使用以下进行反序列化:
$comment = $this->serializer->deserialize($request->getContent(), 'App\Entity\Comment', 'json');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.