Foreign key restriction fails due to nested instruction not yet executed (MySQL)

I have a PHP script using Doctrine 2 that does 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 get integrity violation:

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

My assumption is that the constraint is checked before committing, and it does not check if the insert I inserted did not enter, which has not yet been committed, instead of compromising the constraint. But I really need these two insert statements enclosed in one transaction. So what can I do?

UPDATE

I moved $em->persist($aObject); $em->flush(); $em->persist($aObject); $em->flush(); from a transaction, and I still get the same error. Apparently my hunch was wrong ... But then I really don't know what causes 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 

ForeignTable table

 CREATE TABLE `ForeignTable` ( `ID` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci 
+4
source share
2 answers

I would advise reading about MySQL and FKs data integrity, then the Doctrine Association , data integrity is checked by MySQL tables for InnodDB. What you do wrong 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(); }); 
+1
source

I solved the problem. It was somewhere else completely unrelated to my question .. I am going to accept the getme answer, because accepting this answer really will not help anyone else here ...

0
source

Source: https://habr.com/ru/post/1444198/


All Articles