Skip to content
On this page

Prisma 数据建模

Prisma Schema 语言 (PSL) 提供了一种直观的方式来定义数据库模型。本章将详细介绍如何使用 Prisma 进行数据建模。

基础模型定义

一个简单的模型定义如下:

model User {
  id    Int     @id @default(autoincrement())
  email String  @unique
  name  String?
  posts Post[]
}

字段类型

Prisma 支持多种字段类型:

  • String - 字符串
  • Int - 整数
  • Float - 浮点数
  • Boolean - 布尔值
  • DateTime - 时间戳
  • Json - JSON 对象
  • Bytes - 二进制数据

属性 (Attributes)

字段属性用于定义数据库行为:

  • @id - 主键
  • @unique - 唯一键
  • @default() - 默认值
  • @updatedAt - 自动更新时间戳

关系定义

一对一关系

model Profile {
  id     Int    @id @default(autoincrement())
  userId Int    @unique
  user   User   @relation(fields: [userId], references: [id])
}

model User {
  id       Int      @id @default(autoincrement())
  profile  Profile?
}

一对多关系

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

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

多对多关系

model Post {
  id         Int    @id @default(autoincrement())
  title      String
  categories Category[]
}

model Category {
  id    Int    @id @default(autoincrement())
  name  String
  posts Post[]
}

映射数据库表名

使用 @@map 属性映射数据库表名和列名:

model User {
  id    Int    @id @default(autoincrement())
  email String @unique @map("email_address")

  @@map("users_table")
}

索引定义

在模型级别定义复合索引:

model User {
  id    Int    @id @default(autoincrement())
  email String
  name  String

  @@index([email, name])
}

总结

Prisma Schema 语言提供了一种强大而直观的方式来定义数据模型,使数据库设计变得更加简单和可维护。