diff --git a/src/AppBundle/Controller/BlogController.php b/src/AppBundle/Controller/BlogController.php index cf0ff4ae3..38c42b03c 100644 --- a/src/AppBundle/Controller/BlogController.php +++ b/src/AppBundle/Controller/BlogController.php @@ -94,7 +94,8 @@ public function commentNewAction(Request $request, Post $post) { $comment = new Comment(); $comment->setAuthor($this->getUser()); - $comment->setPost($post); + + $post->addComment($comment); $form = $this->createForm(CommentType::class, $comment); diff --git a/src/AppBundle/DataFixtures/ORM/PostFixtures.php b/src/AppBundle/DataFixtures/ORM/PostFixtures.php index bc0553200..d441bdf53 100644 --- a/src/AppBundle/DataFixtures/ORM/PostFixtures.php +++ b/src/AppBundle/DataFixtures/ORM/PostFixtures.php @@ -66,10 +66,10 @@ public function load(ObjectManager $manager) $comment->setAuthor($this->getReference('john-user')); $comment->setPublishedAt(new \DateTime('now + '.($i + $j).'seconds')); $comment->setContent($this->getRandomCommentContent()); - $comment->setPost($post); - $manager->persist($comment); $post->addComment($comment); + + $manager->persist($comment); } $manager->persist($post); diff --git a/src/AppBundle/Entity/Post.php b/src/AppBundle/Entity/Post.php index 77e6f6bd1..dc1c2ed2a 100644 --- a/src/AppBundle/Entity/Post.php +++ b/src/AppBundle/Entity/Post.php @@ -203,13 +203,17 @@ public function getComments() public function addComment(Comment $comment) { - $this->comments->add($comment); - $comment->setPost($this); + if (!$this->comments->contains($comment)) { + $this->comments->add($comment); + $comment->setPost($this); + } } public function removeComment(Comment $comment) { - $this->comments->removeElement($comment); + if ($this->comments->removeElement($comment)) { + $comment->setPost(null); + } } public function getSummary()