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

{
    "title": "My comment",
    "content": "This is a comment",
    "article": {
        "id": 1
    }
}
  • Article with id 1 exists

I would like the relationship with Article to be deserialized:

 #[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 ?



Solution 1:[1]

Try to use following for deserialization:

$comment = $this->serializer->deserialize($request->getContent(), 'App\Entity\Comment', 'json');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ahuemmer