【问题标题】:Reset Doctrine 2 ID重置教义 2 ID
【发布时间】:2016-07-04 15:14:28
【问题描述】:

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

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

我已尝试删除表、重置身份或 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();
}

提前致谢。

【问题讨论】:

    标签: php database postgresql doctrine-orm integration-testing


    【解决方案1】:

    这里的问题与教义无关。 MySQL 将下一个可用的主键保存在表元数据中。您可以通过执行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');
    

    【讨论】:

    • 谢谢,我使用的是 Postgres,所以我必须使用 $connection->executeQuery('ALTER SEQUENCE bundle_id_seq RESTART WITH 1');
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 2012-02-10
    • 2012-07-20
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    相关资源
    最近更新 更多