Relation ManyToOne - 我的实体的无法识别的字段

时间:2013-01-24 11:30:52

标签: php symfony

我在SYmfony2上做了一个简单的博客引擎。

我有2个实体评论和文章与评论方面的ManyToOne相关。

// Comment.php
/**
* @ORM\ManyToOne(targetEntity="Am\BlogBundle\Entity\Article")
* @ORM\JoinColumn(nullable=false)
*/
private $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');
}

事实上,我想只将评论与我的文章联系起来并与标签相同:/

我不知道我做错了什么?一些帮助会很好:)

由于

1 个答案:

答案 0 :(得分:0)

您希望在实体定义中添加onDelete =“CASCADE”,这将添加到数据库中的外键中,因此当您删除文章时,它会自动级联删除相关注释。

/**
 * @ORM\ManyToOne(targetEntity="Am\BlogBundle\Entity\Article")
 * @ORM\JoinColumn(nullable=false, onDelete="CASCADE")
 */
private $article;