Php Doctrine2以静默方式插入数据失败

Php Doctrine2以静默方式插入数据失败,php,mysql,insert,doctrine-orm,Php,Mysql,Insert,Doctrine Orm,我正在使用原则,第一次执行持久化/刷新时,它无法插入数据,但第二次工作,第三次失败: // there is no code executed between any of the attempts $entity = new My\Entity(); $entity->setTag('A'); // just a random field $em->persist($entity); $em->flush(); // INSERT not performed // if

我正在使用
原则
,第一次执行
持久化/刷新
时,它无法插入数据,但第二次工作,第三次失败:

// there is no code executed between any of the attempts

$entity = new My\Entity();
$entity->setTag('A');  // just a random field
$em->persist($entity);
$em->flush();
// INSERT not performed
// if I exit here and check the database, no entry is added

$entity = new My\Entity();
$entity->setTag('B');
$em->persist($entity);
$em->flush();
// INSERT performed
// if I exit here and check the database, 1 entry has been added
// and I can see it's "B"

$entity = new My\Entity();
$entity->setTag('C');
$em->persist($entity);
$em->flush();
// INSERT not performed
// if I exit here and check the database, there is still only 1 entry added
// and I can see it's "B"
以下是我注意到的失败尝试:
-
PHP日志中没有任何内容(
error\u reporting
设置为all,其他条令和PHP问题,包括警告,都会显示在日志中)。
-
SQLLogger
没有显示任何内容(第二次尝试时,它确实显示了
INSERT

一些故障排除步骤:
-我想通过用
DQL
INSERT
查询替换失败的尝试来进一步排除故障,但是:(
-在失败的尝试中实例化
$entity
之前,执行额外的
刷新
,没有任何帮助 -我可以手动向数据库中插入任意数量的条目,即使是第一次尝试,它也能正常工作。
-我对
2.4.0-DEV
也有同样的问题
-我对
2.2.2
也有同样的问题

我可以补充一点,代码是在
PHPunit
测试中执行的,在以前的测试中,我没有遇到问题(即,条令在第一次
persist/flush
时正确执行
INSERT

知道问题可能来自哪里吗?

版本信息:
-
PHP5.4

-
原则2.3.0
pdo_-mysql
driver)
-
MySQL 5.5.24

-
Ubuntu 12.04

-
PHPUnit 3.7.7

更新1: 好的,这是答案的一部分。我在
PHPUnit
setUp()
中使用的一个例程在每次测试之间截断数据库表,似乎解决了这个问题:

  • 如果在每次测试之间截断表,则会出现问题(即一些
    INSERT
    s失败)
  • 如果我不截断,一切都正常
INSERT
s失败的方式似乎比最初想象的更加随机,因为我创建了两个测试,每个测试有3个INSERT(并且只运行了那些)。在每个测试之间截断表时,下面是每个测试中3个INSERT的情况:
-测试1:成功/成功/成功
-测试2:成功/成功/失败(我不像以前那样有失败/成功/失败)

下面是我用来截断表的一段代码:

$cmd = $em->getClassMetadata($className);
$connection = $em->getConnection();
$dbPlatform = $connection->getDatabasePlatform();
$connection->beginTransaction();
try {
    $connection->query('SET FOREIGN_KEY_CHECKS=0');
    $q = $dbPlatform->getTruncateTableSql($cmd->getTableName());
    $connection->executeUpdate($q);
    $connection->query('SET FOREIGN_KEY_CHECKS=1');
    $connection->commit();
}
catch (\Exception $e) {
    $connection->rollback();
}
我从中获得了代码,据我所知,它看起来不错。如果我使用:


我修改了我的模式以测试是否使用外键,这两种情况下我都有相同的问题。

最后,问题似乎发生在:
-在
设置
函数中截断每个测试之间的表。

-仅在
setUpBeforeClass
中实例化一次条令实例(然后我使用
self::$em
访问该实例)

如果我没有截断每个测试
之间的表,或者如果我在
setUp
中实例化我的条令实例,那么一切都正常


我以前喜欢
setUpBeforeClass
,不再喜欢了…

你怎么知道它第一次不工作,第二次失败?因为如果我在第一次尝试后退出并检查数据库,就不会插入任何条目。我会将其添加到代码段中。
$connection = $entityManager->getConnection();
$platform   = $connection->getDatabasePlatform();
$connection->executeUpdate($platform->getTruncateTableSQL('my_table', true /* whether to cascade */));