LoginSignup
2
2

More than 1 year has passed since last update.

【Laravel】外部キー制約を外して削除したいのにCan't DROPエラーが出る

Posted at

環境

Laravel v9.5.1 (PHP v8.1.3)

状況

  • PointWalletテーブル
    外部キー:user_id
  • Userテーブル

PointWalletテーブルの外部キーuser_idを一旦削除してcascadeOnDelete()をつけたい。

public function up()
{
    Schema::table('point_wallets', function (Blueprint $table) {
        //外部キーを外す
        $table->dropForeign('point_wallets_user_id_foreign');
        //カラムを落とす
        $table->dropColumn('user_id');
    });
    Schema::table('point_wallets', function (Blueprint $table) {
        $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    });
}

下記のエラーでmigration失敗する。

 Syntax error or access violation: 1091 Can't DROP 'point_wallets_user_id_foreign'; check that column/key exists (SQL: alter table `point_wallets` drop foreign key `point_wallets_user_id_foreign`)

原因と解決法

テーブル作成当初から外部キーを張っていて途中でテーブル名を変えた場合、作成当初のテーブル名を使ったカラム名で指定しないとmigrationに失敗する。
(PointWalletテーブルは以前UserPointテーブルだった)

Schema::table('point_wallets', function (Blueprint $table) {
    //外部キーを外す
    Schema::disableForeignKeyConstraints();
    $table->dropColumn('user_id');
});

disableForeignKeyConstraintsを使うと当初のカラム名がエラー文に出てくれる。

 Cannot drop column 'user_id': needed in a foreign key constraint 'user_points_user_id_foreign' (SQL: alter table `point_wallets` drop `user_id`)

↑を指定してdropForeignするとmigration成功。

public function up()
{
    Schema::table('point_wallets', function (Blueprint $table) {
        $table->dropForeign('user_points_user_id_foreign');
        $table->dropColumn('user_id');
    });
    Schema::table('point_wallets', function (Blueprint $table) {
        $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    });
}
2
2
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
2
2