2017-09-27 6 views
0

私はsymfony 2.8を使用しています。私はユーザーとブログの間に1対多の関係を作成しました。また、私はブログとコメントの間に一対一の関係を作りました。同様に、ユーザーとコメントの1対多の関係。今、私のコメントの表は、このSymfonyユーザーとブログIDでブログにコメントを保存

コメントテーブルのように見えます

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()が定義された関数が1つあります。しかし、それはまだそのエラーを示しています。 – 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 \ Blog @ 000000000e6df9e9000000000ffff3b56の永続操作をカスケードするように構成されていない、新しいエンティティが 'AppBundle \ Entity \ Comment#blog'この問題を解決するには:この未知のエンティティのEntityManager#persist()を明示的に呼び出すか、カスケードを設定すると、この関連付けが@ManyToOne(..、cascade = {"persist"})などのマッピングで保持されます。問題の原因となっているエンティティが見つからない場合は、AppBundle \ Entity \ Blog#__ toString()を実装してヒントを得てください。 " – Aamir

+0

ここでは$ blogIdを指摘しましたが、コードの$ idは – Aamir

+0

です。オブジェクトを "$ blog = new Blog();"というshowactionメソッドで削除したところ、完全に機能しました。 – Aamir

関連する問題