CakePHP3 How to stop auto increment on auto generated id column


I researched how to stop auto increment of auto generated id column in CakePHP3.

Checked Environment

I researched on MySQL.

  • CakePHP 3.0.9 (Phinx 0.4.4, MySQL 5.6.19)
  • PHP 5.5.9

The command php bin/cake.php bake migration CreateXXXXXXX ... generate a migration code. After that, php bin/cake.php migraitons migrate creates tables in database with auto incremental id columns. How can we stop auto increment on auto generated id column?

migration code to create not auto incremental id column

The answer is below.

'id' => false prevent from auto generation of id column. And 'primary_key' => 'id' sets primary key columns. Id column should be registered with filename

I researched about the way to turn off only AUTO_INCREMENT and not to turn off id column auto generation.

The code to generate id column

According to my research, we can’t turn off only AUTO_INCREMENT. vendor/robmorgan/phinx/src/Phinx/Db/Adapter/MysqlAdapter.php explains.

The following code is 210-230 line of MysqlAdapter.php.

That’s the code to generate id column. In that case, id column is created as integer. And setIdentity(true) make the column auto-incremental, it’s not controlled by parameter. $options['primary_key'] = 'id' equals to 'primary_key' => 'id', as we added above.

When we do not create id column, condition of if and elseif should be false. Our manually added code, 'id' => false, meets this.

The following code is line 992-1020 of the same file, vendor/robmorgan/phinx/src/Phinx/Db/Adapter/MysqlAdapter.php. It reveals that the column will be auto incremental when setIdentity(true) is executed.

From the above, it is clear that id column should be auto-incremental column when it’s created automatically. In other words, you should stop auto-creating of id column to prevent auto increment.

How is the option used?

To prevent auto-increment, 'id' => false is required. Now, how is the option 'primary_key' => 'id' used?

The following code is line 258-280 of MysqlAdapter.php. Here, prepare for setting primary key according to option parameter.

Required Condition

Thank you for reading my article.

From the above, it is clear that option setting, ['id' => false, 'primary_key' => 'id'], and adding id column by addColumn are required. Without 'id' => false, auto incremental id column will be created. Without 'primary_key' => 'id', the id column can’t be the primary key. Of course, using addIndex is ok if you want only indexing, not primary key.