问题
I'm using symfony 2.8, I have created one-to-many relationship between user and blog,(one user many blogs). Also I have created one-to-many relationship between blog and comments. Similarly one-to-many relationship between user and comments as well. Now my comment table looks like this
comment table
id Primary int(11)
user_id Primary int(11)
blog_id Primary int(11)
comment varchar(2000)
created_at datetime
Comment Entity
Comment Entity
Blog Entity
Blog Entity
User Entity
User Entity
Blog controller -> ShowAction method
/**
* @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()));
}
Now when I submit the comment form from blog show page, it is showing me this error
"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."
What I have missed here. Any help is much appreciated. Thanks
回答1:
I don't see a variable called $blogId
in your code, but assuming it is set, you can try:
[Edit: Follow your example to get $blog
]
$blog = $this->getDoctrine()->getRepository(Blog::class)->findOneById($id);
$comment->setBlog($blog);//Pass that entity to the CommentEntity
来源:https://stackoverflow.com/questions/46445457/symfony-save-comments-on-blog-with-user-and-blogid