1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Laravel】マイグレーションにおける外部キー制約の削除とカラムのロールバック

Posted at

概要

Laravelのマイグレーションは、データベースのスキーマ変更やテーブルの作成、変更を行う際に便利な機能です。しかし、外部キー制約が設定されているテーブルでカラムを削除しようとするとエラーが発生することがあります。本記事では、この問題に対する解決策として、外部キー制約を一時的に無効化してカラムを削除し、マイグレーションのロールバックを行う方法を解説します。

発生したエラー

外部キーを貼ったカラムを削除しようとロールバックを実行したところ、Cannot drop columnというエラーが発生しました。
詳しく見てみると、外部キー制約が存在しているため、カラムの削除ができないというものでした。

そこで、ロールバック時に実行されるdownメソッドを見てみます。

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('teams', function (Blueprint $table) {
            $table->dropColumn('user_id');
        });
    }

dropColumnメソッドを使用してカラムを削除する処理は書いていますが、それだけではエラーが出るので外部キー制約も削除する処理を追加しなければいけません。

外部キー制約を削除すれば解決

dowmメソッドに外部キー制約を削除する処理を追加します。

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('teams', function (Blueprint $table) {
            // 追加 (外部キー名は{テーブル名}_{カラム名}_foreign)
            $table->dropForeign('teams_user_id_foreign');
            $table->dropColumn('user_id');
        });
    }

これで無事削除することができます。

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?