2
2

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 3 years have passed since last update.

[Error]Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails

Posted at

はじめに

この記事はプログラミング初学者による備忘録用の記事であり、また、少しでも他の初学者のお役に立てればと思い書いています。

今回は、外部キー制約があるテーブルデータの削除を試みた際に、[Error]Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails というエラーが発生しましたので解決策を記録しておきます。

間違いなどがございましたら、ご指摘のほどよろしくお願い致します。

結論

・新規作成する場合
onDelete('cascade')を使用して「デリート時(on delete)」に対する処理をオプションとして指定する。

Schema::create('articles', function (Blueprint $table) {
//略
 $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
//略

・既にテーブルを作成している場合
外部キーを削除した後に再度外部キー制約を設定し直す。
Laravel では、 dropForeign() メソッドで外部キー制約の削除が可能である。
引数に配列値を渡せば、削除時に自動的に命名規則に従った名前が使用されます。
dropForeign() メソッドで削除後、再度外部キー制約をonDelete('cascade')付きで設定する。

example.php
//略
Schema::table('articles', function (Blueprint $table) {
    $table->dropForeign(['user_id']);
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
//略

エラーの原因

public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
//略
    $table->foreign('user_id')->references('id')->on('users');
        });
    }
//略

上記のように、テーブル作成時にonDelete('cascade')の使用を忘れていた。

まとめ

外部キー制約にonDelete('cascade')を設定することで、削除するレコードに紐づいている複数のレコードもまとめて一括で削除が可能になる。

参考文献

公式ドキュメント6.x データベース マイグレーション

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?