LoginSignup
11
8

More than 5 years have passed since last update.

CakePHP3(Phinx)のMigrationでidの定義を変更する

Posted at

CakePHP3(Phinx)のMigrationでtableをcreateすると、primaryのidカラムは自動的に生成されますが、signed integerでauto_incrementになるので、名前を変えたりvarcharにしたりunsignedにしたり等、変更したい場合は、以下のようにします。

名前を変える

idではない違う名前にしたい場合は、$this->table()idオプションで指定します。

$table = $this->table('new_table_name', ['id' => 'my_id_name']);
$table
    ->addColumn('title', 'string', ['limit' => 100])
    ・・・
    ->create();

自動生成をやめる

$this->table()のオプションで、'id' => falseとすると自動生成されないので、自動生成をやめて、addColumn()で追加します。
primary_keyオプションは、配列にして複数カラムを指定することもできます。

以下はidが varchar(50) なtableを作る例です。

$table = $this->table('new_table_name', ['id' => false, 'primary_key' => 'id']);
$table
    ->addColumn('id', 'string', [
        'default' => null,
        'limit' => 50,
        'null' => false,
    ])
    ->addColumn('title', 'string', ['limit' => 100])
    ・・・
    ->create();

create()の後にchangeColumn()する

デフォルトではidはsignedなintegerになるので、unsignedにするには、create()した後にchangeColumn()すれば良いです。
(signedオプションは、MySQLにのみ適用されるオプションです。)

$table = $this->table('new_table_name');
$table
    ->addColumn('title', 'string', ['limit' => 100])
    ・・・
    ->create();
$table
    ->changeColumn('id', 'integer', [
        'identity' => true,
        'signed' => false,
    ])
    ->save();

'identity' => trueを書かないと、auto_incrementじゃなくなってしまうので注意。

11
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
8