11
1

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.

Prismaで親を削除したときに子供と孫まで削除する(Referential actions)

Posted at

概要

俗に云うCascading deletesの機能です。
Prismaでは2.26.0以降でReferential actionsの機能が使えるます。
日本語の文献が少なく、探すのに苦労したので備忘録です。

定義方法

@relationで定義時に、onDelete: Cascadeを指定することで親が削除された際に子も削除されます。
削除せずにレコードを残したい場合には onDelete: SetNullを指定することでレコードを残すことも出来ます。

model User {
  id    Int    @id @default(autoincrement())
  posts Post[]
}

model Post {
  id     Int          @id @default(autoincrement())
  title  String
  tags   Tag[]
  user   User        @relation(fields: [userId], references: [id], onDelete: Cascade)
  userId Int
}

model Tag {
  id       Int          @id @default(autoincrement())
  tagname  String
  post     Post        @relation(fields: [postId], references: [id], onDelete: Cascade)
  postId   Int
}

参考文献

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?