LoginSignup
0
0

More than 1 year has passed since last update.

【Laravel】migrationでMySQLの外部キー制約を削除するときはインデックスも削除しよう

Posted at

外部キー制約を設定したカラムがあり、
そのカラムの外部キー制約の削除をしたく下記のmigrationファイルを作成・実行した。

<?php

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

return new class extends Migration
{
	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('tests', function (Blueprint $table) {
			$table->dropForeign(['xxx_id']);
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::table('tests', function (Blueprint $table) {
			$table->foreignId('xxx_id')->constrained();
		});
	}
};

phpMyAdminで確認してみると、
外部キーの制約は削除されていたが、
インデックスの欄にキー名、カラムの横の鍵マークが残ったままになってしまっていて気持ち悪い:sob:
スクリーンショット 2023-02-16 10.06.58.png
スクリーンショット 2023-02-16 10.09.14.png

まとめ

キー名を指定してインデックスも一緒に削除するとよい!

<?php

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

return new class extends Migration
{
	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::table('tests', function (Blueprint $table) {
			$table->dropForeign(['xxx_id']);
			$table->dropIndex('tests_xxx_id_foreign'); // これを追加!
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		Schema::table('tests', function (Blueprint $table) {
			$table->foreignId('xxx_id')->constrained();
		});
	}
};

下記のようにカラム名を指定すると、'tests_xxx_id_index'という名前のインデックスを削除するSQLが作成されてエラーになってしまうので注意:no_good:

$table->dropIndex(['xxx_id']);
0
0
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
0
0