人気のPHP WEBアプリケーションフレームワークLaravelのTipsを記録していきます

Laravel で DBモデル(データベース)のカラムを変更(追加)する

1. テーブル変更のパッケージを追加する

composer require doctrine/dbal

2. テーブル「articles」を変更するマイグレーションファイル「add_columns_articles_table」を生成する

add_columns_articles_table は任意の命名でOKですが「作業内容_テーブル名_table」としておくとテーブル作成時のファイルと命名が揃います

php artisan make:migration add_columns_articles_table  --table=articles

3. 生成されたファイル「2018_xx_xx_xxxxxx_add_columns_articles_table.php」にテーブル追加の命令を記述する

例:「articles」テーブルに以下のカラムを追加します

・「status_id」カラムの後ろにint型の「recruit_flg」を追加します
・「recruit_flg」カラムの後ろにint型の「recruit_date」を追加します
    public function up()
    {
        Schema::table('articles', function (Blueprint $table) {
            $table->integer('recruit_flg')->default(0)->after('status_id');    // この行を追加
            $table->dateTime('recruit_date')->nullable()->after('recruit_flg');    // この行を追加
        });
    }

注意:SQLiteでは任意の位置にカラム追加が出来ないようです
回避策 : https://goo.gl/a2atCx

4. マイグレーションを戻す処理を down()メソッドに記述します

    public function down()
    {
        Schema::table('articles', function (Blueprint $table) {
            $table->dropColumn(['recruit_date','recruit_flg']);
        });
    }

5. カラム追加のマイグレーション実行

php artisan migrate

6. 実行したマイグレーションを戻す

php artisan migrate:rollback

以上で、既存のデータベースのデータを削除することなく、カラムを追加できます。

関連エントリー

No.1381
08/26 18:25

edit

モデル
artisan