ManyToMany关系不持久

时间:2018-08-18 09:45:17

标签: php symfony4

我有PostPostTag实体。仅允许自定义用户创建PostTags。在创建帖子时,用户可以选择帖子标签。

我已经使用make:entity命令在Post和PostTag实体之间建立了多对多关系。

问题在于创建帖子并将其附加到所选标签后,关系表为空,并且post.getPostTags()方法未返回任何内容。

PostController -创建方法:

...
    $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();
...

帖子实体

     /**
     * @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;
    }

PostTag实体

     /**
     * @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;
    }

1 个答案:

答案 0 :(得分:0)

您已经将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;
}