Symfony使用user和blogId在博客上保存评论

时间:2017-09-27 10:23:49

标签: php symfony symfony-2.8

我正在使用symfony 2.8,我创建了用户和博客之间的一对多关系,(一个用户很多博客)。我还创建了博客和评论之间的一对多关系。同样,用户和评论之间也存在一对多的关系。现在我的评论表看起来像这样

评论表

id  Primary     int(11) 
user_id  Primary    int(11)
blog_id  Primary    int(11) 
comment             varchar(2000)  
created_at          datetime

评论实体

Comment Entity

博客实体

Blog Entity

用户实体

User Entity

博客控制器 - > ShowAction方法

/**
 * @Route("/blog/show/{id}", name="blog_show")
 */
public function showAction(Request $request,$id)
{
    $blog = $this->getDoctrine()->getRepository(Blog::class)->findOneById($id);
    $comment = new Comment();
    $form = $this->createForm(CommentType::class, $comment);
    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {
        $user = new User();
        $blog = new Blog();
        $comment->setUser($this->getUser());
        $comment->setBlog($blog);
        $em = $this->getDoctrine()->getManager();
        $em->persist($comment);
        $em->flush();
        return $this->redirect($this->generateUrl('blog_show', array('id' => $id)), 301);
    }

    return $this->render('Blog/show.html.twig', array('blog'=> $blog,'form' => $form->createView()));

}

现在,当我从博客显示页面提交评论表单时,它显示我此错误

"A new entity was found through the relationship 'AppBundle\Entity\Comment#blog' that was not configured to cascade persist operations for entity: AppBundle\Entity\Blog@0000000017546b06000000001fededdf. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'AppBundle\Entity\Blog#__toString()' to get a clue."

我在这里错过了什么。任何帮助深表感谢。感谢

1 个答案:

答案 0 :(得分:1)

我的代码中没有看到名为$blogId的变量,但假设已设置,您可以尝试:

[编辑:按照您的示例获取$blog]

$blog = $this->getDoctrine()->getRepository(Blog::class)->findOneById($id);

$comment->setBlog($blog);//Pass that entity to the CommentEntity