简体   繁体   中英

Foreign key constraint fails because insert statement not yet committed (MySQL)

I have a PHP script using Doctrine 2 which does essentially the following:

$entityManager->transactional(function($em) {
    $foreignObject = new DoctrineEntities\ForeignTable();
    $em->persist($foreignObject);
    $em->flush();
    $aObject = new DoctrineEntities\A();
    $aObject->ForeignID = $foreignObject->ID;
    $em->persist($aObject);
    $em->flush();
});

I'm getting an integrity constraint violation:

a foreign key constraint fails (dbName.A, CONSTRAINT A_ForeignID FOREIGN KEY (ForeignID) REFERENCES ForeignTable ( ID ) ON DELETE NO ACTION ON UPDATE NO ACTION)

My guess is that the constraint is checked before the commit, and it doesn't check to see whether an insert I made that hasn't been committed yet might make the constraint pass rather than fail. But I really do want these two insert statements wrapped in the same transaction. So what can I do?

UPDATE

I moved $em->persist($aObject); $em->flush(); $em->persist($aObject); $em->flush(); out of the transaction and I'm still getting the same error. Apparently, my guess was wrong... But then I really don't know what's causing the error.


SQL Context

Table A

CREATE TABLE `A` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `ForeignID` int(11) NOT NULL,
  PRIMARY KEY (`ID`),
  KEY `A_ForeignID` (`ForeignID`),
  CONSTRAINT `A_ForeignID` FOREIGN KEY (`ForeignID`) REFERENCES `ForeignTable` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci

Table ForeignTable

CREATE TABLE `ForeignTable` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci

I'd suggest to read about MySQL data integrity and FKs , then Doctrine associations , data integrity is checked by MySQL for InnodDB tables. What you're doing is not right, it should be

$entityManager->transactional(function($em) {
    $foreignObject = new DoctrineEntities\ForeignTable();
    $em->persist($foreignObject);

    $aObject = new DoctrineEntities\A();
    $aObject->setForeign($foreignObject);
    $em->persist($aObject);

    $em->flush();
});

I solved the problem. It was somewhere else completly unrelated to my question.. I'm going to accept getme's answer instead because accepting this answer really won't help anyone else here...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM