【Laravel】マイグレーション


Laravel公式ドキュメント-マイグレーションの私的アウトプット

準備

マイグレーションを試すためDBも用意した

項目 名前
DBユーザ名 testuser
DB test

マイグレーション

マイグレーションとはDBのバージョンコントロール

マイグレ−ション作成

構文
php artisan make:migration create_テーブル名_table

テーブル名は複数形にする
2つの--create--tableオプションがある。
公式によればこう説明されている

--table--createオプションも、テーブル名とマイグレーションで新しいテーブルを生成するかを指定するために使用できます。これらのオプションは生成するマイグレーションスタブの中へ指定したテーブルをあらかじめ埋め込みます。
参考
Laravel 7.x データベース:マイグレーション

何言ってるかわかんないから以下コマンドを実行

php artisan make:migration create_users1_table
php artisan make:migration create_users2_table --table=users
php artisan make:migration create_users3_table --create=users
php artisan make:migration add_votes_to_users_table --table=users

そうしてわかったことはupメソッドの中でSchemaクラスの静的メソッドが変わる

オプション 説明
--create オプションなしと変わらない
--table すでに存在するテーブルを更新する

マイグレーション構造

メソッド 説明
up 新しいテーブル、カラム、インデックスを追加
down upメソッドの処理をもとに戻す

マイグレーション実行

php artisan migrate[オプション1] [オプション2]

オプション

オプション 説明
:rollback 最後のマイグレーション操作にロールバック
:refresh 最初似ロールバックしてmigrateコマンドを実行。つまりデータベース全体を作り直すのに適してる
:fresh 全テーブル削除後にmigrateコマンドを実行

オプション2

オプション 説明
--seed シード実行

テーブル

テーブル作成

Schema::create('users', function (Blueprint $table) {
    $table->id();
});

テーブル名変更

Schema::createを使う

Schema::rename($from, $to);

テーブル削除

Schema::drop('users');

Schema::dropIfExists('users');

dropdropIfExistsメソッドを使う
dropIfExistsを使っていったほうが良さげかな

カラム

カラム作成

Schema::tableを使う

Schema::table('users', function (Blueprint $table) {
    $table->string('email');
});

テーブル作成のマイグレーションでオプションなしで作成されたファイルに書かれている$table->id();の意味が載っていた↓

カラムタイプ 意味
$table->id(); $table->bigIncrements('id')のエイリアス

カラム修飾子

NULLを許さない定義にするときとかはnullableメソッドを使う

Schema::table('users', function (Blueprint $table) {
    $table->string('email')->nullable();
});

カラム変更

まずは準備

composer require doctrine/dbal

カラム属性の変更

changeメソッドを使う

stringカラムの文字長を変更する例
//文字長を25から50に変更
Schema::table('users', function (Blueprint $table) {
    $table->string('name', 50)->change();
});
NULL値設定可能に変更する例
Schema::table('users', function (Blueprint $table) {
    $table->string('name', 50)->nullable()->change();
});

カラム名変更

renameColumnメソッドを使う
ここで先のcomposerで追加したものを使う

Schema::table('users', function (Blueprint $table) {
    $table->renameColumn('from', 'to');
});

カラム削除

dropColumnメソッドを使う

votesカラムを削除
Schema::table('users', function (Blueprint $table) {
    $table->dropColumn('votes');
});

この引数に配列を渡すと複数カラムを削除できる

複数カラムを削除
Schema::table('users', function (Blueprint $table) {
    $table->dropColumn(['votes', 'avatar', 'location']);
});