Fabian
Fabian

Reputation: 1846

Symfony2: Issue with foreign key when saving OneToOne related entity

I have a simple usecase:

i have done that 1000 times like this. but now something strange happens:

   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`))

I cannot explain what is the problem, because the contactdetails entity is created correctly. it just cannot be saved to the user :/

Edit:

Mapping info (User entity):

/**
 * @ORM\OneToOne(targetEntity="...\FrontendBundle\Entity\Contactdetails")
 */
private $contactdetails;

/**
 * @ORM\OneToOne(targetEntity="...\FrontendBundle\Entity\Medialinks")
 */
private $medialinks;

Upvotes: 0

Views: 159

Answers (1)

xiidea
xiidea

Reputation: 3394

You need to persist the Contactdetails first.

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

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

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

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

Upvotes: 1

Related Questions