LoginSignup
10
5

More than 5 years have passed since last update.

【Laravel】 ユニークな外部キーを定義する方法

Last updated at Posted at 2017-03-15

ユニークな外部キーを作りたいとき,uniqueの第1引数とforeignの第2引数に同じキー名を指定するとインデックスを無駄に2つ作らずに済みます。標準の命名規則はテーブル名_属性名_uniqueまたはテーブル名_属性名_foreignとなっているので,これにちなんでテーブル名_属性名_unique_foreignとか付けると良さそう。

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateEntitiesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('entities', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->unique('entities_user_id_unique_foreign');
            $table->foreign('user_id', 'entities_user_id_unique_foreign')->references('id')->on('users');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('entities');
    }
}
10
5
1

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
10
5