Jakob Alexander Eichler
Jakob Alexander Eichler

Reputation: 3056

How to set an initial auto_increment value using doctrine2

I use the doctrine2 mapper to generate my innoDB (mysql) database. How to set the initial value of my auto_incremented id using the php annotations?

This is how I modelled the id of my entity type at the moment.

/**
 * @var integer $_id
 *
 * @Column(name="id", type="integer", nullable=false)
 * @Id
 * @GeneratedValue(strategy="IDENTITY")
 */
private $_id;

I found the following code in the documentation but it looks as if it would use a separate table to generate the ids.

/**
 * @Id
 * @GeneratedValue(strategy="SEQUENCE")
 * @Column(type="integer")
 * @SequenceGenerator(sequenceName="tablename_seq", initialValue=1, allocationSize=100)
 */

Upvotes: 7

Views: 3438

Answers (3)

Sebastian Viereck
Sebastian Viereck

Reputation: 5915

Here is the complete code example for setting the auto_increment in doctrine 2 in MySQL:

$connection = $this->getEntityManager()->getConnection();
$connection->prepare('ALTER TABLE my_table AUTO_INCREMENT = 100;')->execute();

Upvotes: 2

Radoslav Bodó
Radoslav Bodó

Reputation: 661

not really clear from documentation, but sources says ...

doctrine/dbal/lib/Doctrine/DBAL/Platforms/MySqlPlatform.php:        if (isset($options['auto_increment'])) {
doctrine/dbal/lib/Doctrine/DBAL/Platforms/MySqlPlatform.php:            $tableOptions[] = sprintf('AUTO_INCREMENT = %s', $options['auto_increment']);

so for mysql works as option for @table annotation

* @ORM\Table(name="xxx", options={"auto_increment": 100})

Upvotes: 1

tvlooy
tvlooy

Reputation: 1036

You could set strategy="NONE" and set the last ID in a @prepersist function. More easy would be to just add a "ALTER TABLE something AUTO_INCREMENT = 100;" in a DataFixture or DB migration. It's not portable SQL but it does the job without adding complexity in your Entity.

Upvotes: 1

Related Questions