2017-09-27 123 views
0

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

评语表

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\[email protected] 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." 

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

+0

它告诉你在类中没有叫做getBlog的函数。真的吗? –

+0

如果您检查我的评论实体,则有一个函数定义了getBlog()。但它仍然显示错误。 – Aamir

+0

但是这在'Comment'实体中。当你调用'$ this-> getBlog();'它正在'BlogController'本身寻找这个函数。你需要从表单中获取它吗? –

回答

1

我没有看到一个变量,名为在你的代码$blogId,但假设它被设置,你可以尝试:

[编辑:按照您的例子让$blog]

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

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

它现在向我显示这个错误,“通过关系'AppBundle \ Entity \ Comment#blog'发现了一个新的实体,它没有被配置为级联实体:AppBundle \ Entity \ Blog @ 000000000e6df9e9000000000ffb3b56的持久化操作。解决此问题:显式调用此未知实体上的EntityManager#persist()或配置级联将该关联保存在映射中,例如@ManyToOne(..,cascade = {“persist”})。如果你找不到哪个实体导致问题实现'AppBundle \ Entity \ Blog #__ toString()'以获得线索。“ – Aamir

+0

我在这里提到了$ blogId,但是它的$ id在代码中 – Aamir

+0

这条线覆盖了$ blog对象“$ blog = new Blog();”在showaction方法中,我删除了它,它工作的很完美。 – Aamir