I’m doing a simple Blog engine on SYmfony2.
I have 2 entity Comment and Article who are related with a ManyToOne on Comment side.
// Comment.php
/**
* @ORM\ManyToOne(targetEntity="Am\BlogBundle\Entity\Article")
* @ORM\JoinColumn(nullable=false)
*/
private $article;
When I try to delete an Article, I would like to delete all comments related to this article.
//Am/BlogBundle/Controller/BlogController.php
public function delArticleAction(Article $article)
{
$em = $this->getDoctrine()
->getEntityManager();
$list_tags = $em->getRepository('AmBlogBundle:Tag')
->findAll();
$list_comments = $em->getRepository('AmBlogBundle:Comment')
->findBy(array('article_id'=>$article->getId()));
//In order to delete an article, we have to remove each object linked to an Article
foreach($list_tags as $value){
$article->removeTags($value);
}
foreach($list_comments as $value){
//We delete all the comments of an article
$em = $this->getDoctrine()->getManager();
$em->remove($value);
$em->flush();
}
// We remove the Article
$em = $this->getDoctrine()->getManager();
$em->remove($article);
$em->flush();
return $this->render('AmBlogBundle:Blog:delArticle.html.twig');
}
In fact, I would like to get only the Comment tied to my Article and goes the same with Tags :/
I don’t know what am I doing wrong ? Some help would be nice 🙂
Thanks
You want to add onDelete=”CASCADE” in your entity definition and this will be added to the foreign key in the database, so when you delete an Article, it will cascade delete related comments automatically.