dongwen9947 2012-11-05 19:57
浏览 127
已采纳

外键约束失败,因为insert语句尚未提交(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(); 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
  • 写回答

2条回答 默认 最新

  • double2022 2012-11-06 17:45
    关注

    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();
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog