php - 重置学说 2 ID

标签 php database postgresql doctrine-orm integration-testing

我正在进行集成测试,但无法直接为实体设置 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();
}

提前致谢。

最佳答案

这里的问题与教义无关。 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');

关于php - 重置学说 2 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38187905/

相关文章:

mysql - 我怎么做这个sql技巧

sql - 将数据从一个表复制到另一个不同的列名称

sql - PostgreSQL 分组滚动平均值

python - 在不覆盖数据库的情况下推送到 Heroku

php - 比较php中的两个字符串并显示字符差异

PHP - Fulifilm 照片的 exif 数据损坏

php - 创建图像的缩略图,然后将其保存到数据库中

php - 如何将数组传递给 laravel 5.4 中的@slot?

linux - 无法运行 rake db :migrate, 关系不存在

java - 我的代码没有打印