1

I'm doing integration testing and I can't directly set an ID to an entity. What I need is, somehow tell Doctrine to reset ID to 1.

When I call flush I get IDs 20, 21, then 22,23.

I have tried deleting table, reseting identity or this thread but nothing helps.

My code:

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();
}

Thanks in advance.

John Dare
  • 13
  • 1
  • 3

1 Answers1

4

The problem is not doctrine related here. MySQL keeps the next available primary key stored in the table meta-data. You can "reset" or alter the value by executing an ALTER TABLE query:

ALTER TABLE your_table AUTO_INCREMENT = 1;

Or, in a doctrine migration:

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

If you're not using the doctrine migration bundle, you can write a one-off script and, using the entity manager:

$em->getConnection()->exec('ALTER TABLE your_tbl AUTO_INCREMENT = 1');
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • 2
    Thanks, I'm using Postgres, so I have to use $connection->executeQuery('ALTER SEQUENCE bundle_id_seq RESTART WITH 1'); – John Dare Jul 07 '16 at 08:05