LoginSignup
3
4

More than 3 years have passed since last update.

【laravel】migrationでindexをつけたときのメモ

Posted at

毎回調べるのが面倒になったのでまとめました
全てmigrationファイル上での記述です。
参考 : https://laravel.com/docs/5.8/migrations

1. 基本的なキー作成

Schema::create('members', function (Blueprint $table) {
    $table->integer('id')->primary(); //プライマリキー
    $table->string('email')->unique(); //ユニークキー
    $table->string('name')->index();  //indexキー
});

laravelではキーを作成するときに「テーブル名+カラム名+キー」の命名規則で自動で名前をつけてくれる。
(上記の例だとmembers_name_index, members_email_uniqueという名前になる)

名前を自分で付けたいとき

引数に任意のキー名を入れる

Schema::create('members', function (Blueprint $table) {
    $table->string('email')->unique('email_unique'); 
    $table->string('name')->index('name_index');
});

2. 複合キー

カラムの配列を渡す
(名前を自分でつけたいときは同じく第二引数で指定する)

Schema::create('members', function (Blueprint $table) {
    $table->integer('id'); 
    $table->string('email'); 
    $table->string('name');
    $table->unique(['email', 'name']); //複合ユニークキー
    $table->index(['id', 'email'], 'members_index'); //複合index(任意の名前をつける)
});

キーの削除

第一引数に削除するキーの名前を渡す
(laravelの命名規則に則っている場合は、カラム名の配列を渡して指定することもできる)

Schema::table('members', function (Blueprint $table) {
    $table->dropUnique('members_email_unique'); //キー名を指定して削除
    $table->dropIndex(['name']); //members_name_indexを削除
});

3
4
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
3
4