Symfony序列化器和ManyToMany setter

我有两个实体。 书和作者

class Book
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private int $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private string $name;

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Author", fetch="EXTRA_LAZY")
     * @ORM\JoinTable(name="books_authors",
     *     joinColumns={@ORM\JoinColumn(name="book_id", referencedColumnName="id")},
     *     inverseJoinColumns={@ORM\JoinColumn(name="author_id", referencedColumnName="id")}
     *  )
     * @var PersistentCollection|ArrayCollection
     */
    private $authors;

    public function __construct()
    {
        $this->authors = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getAuthors()
    {
        return $this->authors;
    }

    public function setAuthors($authors)
    {
        $this->authors = $authors;
    }

    public function addAuthor($author){
        if(!$this->authors->contains($author))
            $this->authors->add($author);
    }

    public function  removeAuthor($author){
        if($this->authors->contains($author)){
            $this->authors->removeElement($author);
        }
    }
}

在BookController中,我尝试创建新书并使用序列化器 书身像

{
  "name:"book name",
  "authors":[
    1,
    2
  ]
}

在控制器中

$serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
$book = $this->serializer->deserialize($request->getContent(), Book::class, 'json');
        try{
            $this->entityManager->persist($book);
            $this->entityManager->flush();
        } catch (UniqueConstraintViolationException $exception){
            return new JsonResponse('already exist', JsonResponse::HTTP_FOUND);
        }

but on flush() i have exception: Expected value of type "App\Entity\Author" for association field "App\Entity\Book#$authors", got "integer" instead. because book->authors now is id collection, but entity collection needle. I have some variants of resolve this, but what is the best way for create and update entity?

评论