Symfony2:保存OneToOne相关实体时出现外键问题

时间:2014-04-04 11:09:52

标签: symfony entity

我有一个简单的用例:

  • 我创建了一个contactdetails实体
  • 我创建了一个用户实体
  • 我将新的contactdetails对象添加到具有$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;

1 个答案:

答案 0 :(得分:1)

您需要先保留 Contactdetails

$em = $this->getDoctrine()->getManager();

$contactdetails = new Contactdetails();
$em->persist($contactdetails);

$user = new User();
$user->setContactdetails($contactdetails);

$em->persist($user);
$em->flush();