ManyToMany 关系不持久

ManyToMany relation is not persisted

我有 PostPostTag 个实体。仅允许自定义用户创建 PostTags。创建 post 用户可以 select post 标签。

我使用 make:entity 命令在 Post 和 Post 标记实体之间创建了多对多关系。

问题是在创建 post 并将 selected 标签附加到它之后,关系 table 是空的 什么都没有由 post.getPostTags() 方法返回。

Post控制器 - 创建方法:

...
    $em = $this->getDoctrine()->getManager();

    $post = $form->getData();
    $post->setAuthor($this->getUser());
    $post->setCreatedAt(new DateTime);
    foreach ($form->get('post_tags')->getData() as $postTag) {
         $post->addPostTag($postTag);
    }
    $em->persist($post);
    $em->flush();
...

Post 实体:

     /**
     * @ORM\ManyToMany(targetEntity="App\Entity\PostTag", mappedBy="post", cascade={"persist"})
     */
    private $postTags;



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

    /**
     * @return Collection|PostTag[]
     */
    public function getPostTags(): Collection
    {
        return $this->postTags;
    }

    public function addPostTag(PostTag $postTag): self
    {
        if (!$this->postTags->contains($postTag)) {
            $this->postTags[] = $postTag;
            $postTag->addPost($this);
        }

        return $this;
    }

    public function removePostTag(PostTag $postTag): self
    {
        if ($this->postTags->contains($postTag)) {
            $this->postTags->removeElement($postTag);
            $postTag->removePost($this);
        }

        return $this;
    }

Post标记实体:

     /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Post", inversedBy="postTags", cascade={"persist"})
     */
    private $post;

    public function __construct()
    {
        $this->post = new ArrayCollection();
    }
    /**
     * @return Collection|Post[]
     */
    public function getPost(): Collection
    {
        return $this->post;
    }

    public function addPost(Post $post): self
    {
        if (!$this->post->contains($post)) {
            $this->post[] = $post;
        }

        return $this;
    }

    public function removePost(Post $post): self
    {
        if ($this->post->contains($post)) {
            $this->post->removeElement($post);
        }

        return $this;
    }

您已将 PostTag 实体设置为拥有方(通过在该实体上设置 inversedBy 参数),因此您必须保留 PostTag 实体,不是 Post 实体,让事情坚持下去。您可以对您的 Post 实体进行简单修改以使其工作:

public function addPostTag(PostTag $postTag): self
{
    if (!$this->postTags->contains($postTag)) {
        $this->postTags[] = $postTag;
        $postTag->addPost($this);

        // set the owning side of the relationship
        $postTag->addPost($this);
    }

    return $this;
}