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

Prismaのフィールド修飾子についてまとめてみた

Posted at

Prismaのスキーマの修飾子をまとめてみました

基本

@id

フィールドを主キーとして定義

model User {
  id Int @id @default(autoincrement())
}

@default

フィールドのデフォルト値を設定

model Post {
  createdAt DateTime @default(now())
  published Boolean @default(false)
  viewCount Int @default(0)
}

@unique

フィールドに一意制約

model User {
  email String @unique
}

@relation

モデル間のリレーションシップを定義

model Post {
  author User @relation(fields: [authorId], references: [id])
  authorId Int
}

マッピング

@map

フィールド名をdb上の列名に変換

model User {
  firstName String @map("first_name")
}

@@map

モデル名をdb上のテーブル名に変換

model User {
  id Int @id
  
  @@map("users")
}

データベース固有の修飾子

@db

データベースにこの形式で保存してね

model User {
  id String @id @default(uuid()) @db.Uuid
  
  createdAt DateTime @db.Timestamptz(6)
}

複合インデックスと制約

@@index

複数のフィールドを組み合わせて検索する時に、検索を速くするための設定

model Post {
  title String
  content String
  
  // title と content を組み合わせた検索を速くする
  @@index([title, content])
}

@@unique

複数のフィールドの組み合わせが一意(重複しない)であることを保証する
→ 1つの投稿に対し、いいねを1回までに制限

model Like {
  userId Int
  postId Int
  
  @@unique([userId, postId])
}
1
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
1
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?