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・Rails】親が削除されたらリレーション先の子テーブルも削除する方法まとめ

Posted at

環境

Laravel v9.5.1 (PHP v8.1.3)

Laravel

cascadeOnDelete()

マイグレーションファイルでやる方法。

Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
});

deleting()

modelにロジックを書く方法。

app/Models/User.php
protected static function boot()
{
   parent::boot();

   self::deleting(function ($user) {
      $user->posts()->delete();
   });
}

Rails

on_delete: :cascade

マイグレーションファイルでやる方法。

add_foreign_key :users, :posts, on_delete: :cascade

dependent: :destroy

modelにロジックを書く方法。
個人的にこれをよく使ってた。

models/user.rb
has_many :posts, dependent: :destroy
models/post.rb
belongs_to :user
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?