我有一个简单的用例:
$user->setContactdetails($contactdetails);
然后我坚持
$contactdetails = new Contactdetails();
$user = new User();
$user->setContactdetails($contactdetails);
$em = $this->getDoctrine()->getManager();
$em->persist($contactdetails);
$em->persist($user);
$em->flush();
我这样做了1000次。但现在出现了一些奇怪的事情:
An exception occurred while executing 'INSERT INTO user (contactdetails_id) VALUES (?)' with params [2175]:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`inscouts`.`user`, CONSTRAINT `FK_8D93D64998778544` FOREIGN KEY (`contactdetails_id`) REFERENCES `Contactdetails` (`id`))
我无法解释是什么问题,因为contactdetails实体是正确创建的。它只是无法保存到用户:/
修改
映射信息(用户实体):
/**
* @ORM\OneToOne(targetEntity="...\FrontendBundle\Entity\Contactdetails")
*/
private $contactdetails;
/**
* @ORM\OneToOne(targetEntity="...\FrontendBundle\Entity\Medialinks")
*/
private $medialinks;
答案 0 :(得分:1)
您需要先保留 Contactdetails 。
$em = $this->getDoctrine()->getManager();
$contactdetails = new Contactdetails();
$em->persist($contactdetails);
$user = new User();
$user->setContactdetails($contactdetails);
$em->persist($user);
$em->flush();