Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine: Explicitly giving primary key value while not changing the auto increment

There is a table with many columns along with primary key column 'id' having auto increment attribute. The database is mySQL.

There are two kinds of PHP code that are inserting in that column. 1.) Normal insert queries are created as string and are executed by making ADO connection to the database.In this case, primary key value is not provided so it uses the table's auto increment value.

2.) There is an php symfony doctrine's entity class with primary field declared as

/**
     * @var int
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     */
    private $id;

The insertion uses the entity manager's persist method. Here while inserting, the id value is explicitly provided which is far greater than the column's auto increment value. That's why the Generation_Type is ommited in the annotations.

Now, let's say the current auto_increment value is 10000. I want that while executing the first scenario, the next id is taken as 1001 which is expected. But in case of executing the second scenario with explicit id = 2000, it inserts the record with 2000 but does not change the auto_increment to 2000. It should still remain to 1001.

Do I have to make changes around this piece of code?

$this->em->persist(obj);

Thanks in advance.

like image 498
Dhruv Sharma Avatar asked Sep 14 '25 08:09

Dhruv Sharma


1 Answers

If you don't need your Doctrine Entity to ever use the AUTO strategy to set the Id value you should simply be able to use the NONE strategy

/**
 * @ORM\Column(type="integer")
 * @ORM\Id()
 * @ORM\GeneratedValue(strategy="NONE")
 */
private $id;

More infos on the available strategies can be found here: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/basic-mapping.html#identifier-generation-strategies

If you need your Entity to have an auto increment strategy in the normal workflow you can set it to AUTO and disable that at a needed time by:

$metadata = $entityManager->getClassMetadata(get_class($entity));
$metadata->setIdGeneratorType(ClassMetadata::GENERATOR_TYPE_NONE);
$em->persist($entity);
$em->flush();

General disclaimer: proceed with caution!

like image 116
Joe Avatar answered Sep 15 '25 23:09

Joe