I have Post
And PostTag
entities. Only custom users are allowed create PostTags
. While creating a post user may select post tags.
I have created many to many relationship between Post And PostTag entities using the make:entity
command.
The problem is that after creating the post and attaching to it the selected tags the relation table is empty and nothing is returned by post.getPostTags()
method.
PostController - create method:
...
$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 entity:
/**
* @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 entity:
/**
* @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;
}