我是Symfony的新手,我正在嘗試做一個簡單的Blog。我有我的數據庫中的用戶作爲評論的作者和兩種類型的評論 - PostComment和ReplyComment,它們都擴展了抽象類的評論。我想評論保存到數據庫,但我堅持了這個錯誤:Symfony3學說單表無罪SQLSTATE [23000]:完整性約束違規
發生異常而執行「INSERT INTO評論(文字, AUTHOR_ID,POST_ID,comment_type)VALUES(,,??? ?)」使用參數 [ 「Lorem存有」,1,1, 「post_comment」]:
SQLSTATE [23000]:完整性約束違規:1452不能添加或 更新子行,外鍵約束失敗 (
blog_symfony
。comment
,CONSTRAINTFK_9474526CDB1174D2
FOREIGN KEY(post_comment_id
)參考文獻comment
(id
))
這是抽象的註釋類別:
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
* @ORM\Table(name="comment")
* @ORM\InheritanceType("SINGLE_TABLE")
* @ORM\DiscriminatorColumn(name="comment_type", type="string")
* @ORM\DiscriminatorMap({"post_comment" = "PostComment", "reply_comment" = "ReplyComment"})
*/
abstract class Comment
{
/**
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\User", inversedBy="userComments")
*/
protected $author;
/**
* @ORM\Column(type="string")
*/
protected $text;
/**
* @return integer $id
*/
public function getId()
{
return $this->id;
}
/**
* @return string $author
*/
public function getAuthor()
{
return $this->author;
}
/**
* @param string $author
*/
public function setAuthor($author)
{
$this->author = $author;
}
/**
* @return string $text
*/
public function getText()
{
return $this->text;
}
/**
* @param string $text
*/
public function setText($text)
{
$this->text = $text;
}
}
這是一個張貼評論類
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="AppBundle\Repository\PostCommentRepository")
*/
class PostComment extends Comment
{
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Post", inversedBy="comments")
* @ORM\JoinColumn(nullable=true, onDelete="SET NULL")
*/
private $post;
/**
* @ORM\OneToMany(targetEntity="AppBundle\Entity\ReplyComment", mappedBy="postComment", cascade={"remove"}, orphanRemoval=true)
* @ORM\OrderBy({"id"="DESC"})
*/
private $replyComments;
/**
* @return replyComment[] reply comments
*/
public function getReplyComments()
{
return $this->replyComments;
}
/**
* @param replyComment[] reply comments
*/
public function setReplyComments($replyComments)
{
$this->replyComments = $replyComments;
}
/**
* @return Post post
*/
public function getPost()
{
return $this->post;
}
/**
* @param Post post
*/
public function setPost($post)
{
$this->post = $post;
}
}
最後這是在控制器運行過程中出現的邏輯
代碼if ($postCommentForm->isSubmitted() && $postCommentForm->isValid())
{
/** @var PostComment $comment */
$comment = $postCommentForm->getData();
$comment->setPost($post);
$author = $this->getDoctrine()->getRepository('AppBundle:User')->findOneBy([
'email' => $comment->getAuthor()
]);
$comment->setAuthor($author);
$em = $this->getDoctrine()->getManager();
$em->persist($comment);
$em->flush();
return $this->redirectToRoute("single_post", [
'id' => $post->getId()
]);
}
它沒有,感謝ü:) –
那麼你可以檢查答案 – Rawburner
我的意思是接受它 – Rawburner