重置学说 2 ID

Reset Doctrine 2 ID

我正在进行集成测试,无法直接为实体设置 ID。我需要的是,以某种方式告诉 Doctrine 将 ID 重置为 1。

当我调用 flush 时,我得到 ID 20、21,然后是 22,23。

我曾尝试删除 table、重置身份或此 thread,但无济于事。

我的代码:

public function testFindingAllOrderedByDefault()
{
    /** @var $bundles Bundle[] */
    $bundles = $this->repository->findAll();
    $this->assertCount(2, $bundles);
    $this->assertSame(1, $bundles[0]->getId());
    $this->assertSame(2, $bundles[1]->getId());
}

protected function prepareDatabase(EntityManager $entityManager, Connection $connection)
{
    $connection->executeQuery('TRUNCATE bundle CASCADE');
    $entityManager->persist(
        (new Bundle())
            ->setPrice(1200)
            ->setPriceVat(5000)
            ->setDiscount(1000)
            ->setCurrency('czk')
    );
    $entityManager->persist(
        (new Bundle())
            ->setPrice(1300)
            ->setPriceVat(4000)
            ->setDiscount(500)
            ->setCurrency('eur')
    );
    $entityManager->flush();
}

提前致谢。

这里的问题与教义无关。 MySQL 将下一个可用的主键存储在 table 元数据中。您可以 "reset" 或通过执行 ALTER TABLE 查询来更改值:

ALTER TABLE your_table AUTO_INCREMENT = 1;

或者,在学说迁移中:

public function up(Schema $schema)
{
    $this->connection->exec('ALTER TABLE your_table AUTO_INCREMENT = 1');
}

如果您不使用学说迁移包,您可以编写一个一次性脚本,并使用实体管理器:

$em->getConnection()->exec('ALTER TABLE your_tbl AUTO_INCREMENT = 1');