2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Yii2のmigrationファイル作成コマンド

Last updated at Posted at 2020-04-04

概要

Yii2のmigrationファイル作成コマンドは実行時に指定するオプションによって生成するテンプレートがことなります。

migrationファイル作成コマンド

内容 コマンド 参照するテンプレートパス
テーブル作成 yii migrate/create create_xxx_table @yii/views/createTableMigration.php
テーブル削除 yii migrate/create drop_xxx_table @yii/views/dropTableMigration.php
カラム追加 yii migrate/create add_columns_to_xxx_table @yii/views/addColumnMigration.php
カラム削除 yii migrate/create drop_columns_from_xxx_table @yii/views/dropColumnMigration.php
その他 yii migrate/create <name> @yii/views/migration.php

xxxにはテーブル名が入ります。
<name>は任意の文字列が入ります。

fieldsオプション

migrateコマンド実行時にfieldsオプションでカラムの情報を指定できます。
カラム追加/カラム削除の時に filedsオプションを指定するとカラムが自動で入るので便利です。

# user テーブルにemail カラムを追加する場合
yii migrate/create add_columns_to_user_table --fields="email:string"

生成されるコード

add_columns_to_user_table.php
    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        $this->addColumn('{{%user}}', 'email', $this->string());
    }

    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        $this->dropColumn('{{%user}}', 'email');
    }

migrationのテンプレート

テーブル作成時に登録日時など入るカラムがある場合、あらかじめテンプレートに追加しておくと便利です。
created_at/updated_atカラムをあらかじめ追加したテンプレート。

@yii/views/_createTable.php
        $this->createTable('<?= $table ?>', [
            // ~~ 省略 ~~
            'created_at' => $this->datetime()->notNull()->defaultExpression('CURRENT_TIMESTAMP')->comment('登録日時'),
            'updated_at' => $this->datetime()->notNull()->defaultExpression('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')->comment('更新日時'),
        ]);

もとのテンプレートを変更したくない場合は、migration実行時に --templateFile=テンプレートパス をつけることで独自のテンプレートを使用することもできます。

参考

Yii 2.0 決定版ガイド データベース・マイグレーション

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?