LoginSignup
10
5

More than 5 years have passed since last update.

Laravel migrateでdropUnique行う時に「needed in a foreign key constraint」が発生する場合の対応

Last updated at Posted at 2018-06-27

前提(というか私の環境)

Laravel 5.5
PHP 7.0

起きたこと

開発環境のDBをクリアしようと以下コマンドを実行したところ、、、

php artisan migrate:refresh --seed

マイグレーションのロールバックに失敗する!!!

In Connection.php line 664:

  SQLSTATE[HY000]: General error: 1553 Cannot drop index 'xxxxxxxxxx_unique_index': needed in a foreign key constraint (SQL: alter table `xxxxxxxxxx` drop index `xxxxxxxxxx_unique_index`)


In Connection.php line 458:

  SQLSTATE[HY000]: General error: 1553 Cannot drop index 'xxxxxxxxxx_unique_index': needed in a foreign key constraint

対応

外部キー制約でエラーが発生してしまっているので、外部キー制約を一時的にとっぱらうよう記述する
https://readouble.com/laravel/5.5/ja/migrations.html#foreign-key-constraints

public function down()
{
    Schema::disableForeignKeyConstraints();
    Schema::table('xxxxxxxxxx', function (Blueprint $table) {
        $table->dropUnique('xxxxxxxxxx_unique_index');
    });
    Schema::enableForeignKeyConstraints();
}

もしかして、テーブル設計がそもそも間違ってたかな……。

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