【Laravel】外部接続のインデックスを任意の名前に変更する

マイグレーションで外部接続を設定する時に、設定するテーブル名や外部きーが長いと次のようなエラーが出ます。

Syntax error or access violation: 1059 Identifier name 'xxxxxx_foreign' is too long is too long.

この場合、短いインデックスを指定する必要があります。
今回は、任意のインデックスを設定する方法について解説します。

初期設定時の命名について

laravelのデフォルト設定では、外部接続のインデックスを次のように指定します。

(接続元テーブル名)_(接続先テーブル名) _(外部接続キー)_foreign

例えば、下記のような中間テーブルを作るとします。

<?php
class CreateHogeFugaTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('hogehoge..._fugafuga...', function (Blueprint $table) {
            $table->unsignedInteger('hoge_id');
            $table->foreign('hoge_id')
                ->references('id')
                ->on('hogehoge...')
                ->onDelete('cascade');
            $table->unsignedBigInteger('fuga_id');
            $table->foreign('fuga_id')
                ->references('id')
                ->on('fugafuga...')
                ->onDelete('cascade');
            $table->primary(['hoge_id', 'fuga_id']);
        });
    }
}    

この場合、インデックスはhoge...テーブルとfuga...テーブルを接続するためのインデックスは次のようになります。

hoge..._fuga..._hoge_id_foreign

任意のインデックスを指定する

インデックスを指定するには、foreign()の第二引数にインデックスを指定します。
前項のマイグレーションを元に解説すると次のように指定します。

<?php
class CreateHogeFugaTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('hogehoge..._fugafuga...', function (Blueprint $table) {
            $table->unsignedInteger('hoge_id');
            $table->foreign('hoge_id', 'h_f_foreign')
                ->references('id')
                ->on('hogehoge...')
                ->onDelete('cascade');
            $table->unsignedBigInteger('fuga_id');
            $table->foreign('fuga_id', 'f_h_foreign')
                ->references('id')
                ->on('fugafuga...')
                ->onDelete('cascade');
            $table->primary(['hoge_id', 'fuga_id']);
        });
    }
}    

©︎2017-2018 WebSandBag