Help us understand the problem. What is going on with this article?

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

ユニークな外部キーを作りたいとき,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');
    }
}
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away