LoginSignup
17
16

More than 5 years have passed since last update.

cakePHP3でbake migrate

Posted at

cakePHP3はPhinxというマイグレーションライブラリを使用しています。
とりあえず、DBには何もテーブルが作られていないという前提で、

./bin/cake bake migration MigrationName

というbakeコマンドを叩くと、MigrationNameがついたファイルが、config/Migrationsの下に作成されます。
ファイル名は、日付_migration_name.php。
初期状態だと、中身は下記です。

日付_migration_name.php
<?php
use Phinx\Migration\AbstractMigration;

class MigrationName extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
    }
}

ここに、Phonxのドキュメントにあるコードをモジって書いてみます。

日付_migration_name.php
    public function change()
    {
        $table = $this->table('tags');
        $table->addColumn('tag_name', 'string')
              ->create();

        $refTable = $this->table('tag_relationships');
        $refTable->addColumn('tag_id', 'integer')
                 ->addForeignKey('tag_id', 'tags', 'id')
                 ->create();
    }

で、マイグレーションを実行します。

./bin/cake migrations migrate

エラーが出ずに、AllDoneと表示されれば成功です。
tagsとtag_relationshipsというテーブルが作成されていると思います。

おまけ

addForeignKeyをするときに、ちょっとハマりました。
ドキュメントには、array('delete'=> 'SET_NULL', 'update'=> 'NO_ACTION')というオプションを指定しているのですが、対象のカラム(id)はNULLを許可してないため、エラーになったのだと思います。

17
16
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
17
16