什么是 Model?
在 Prisma 中,Model 是数据库表的抽象定义。每一个 Model 对应数据库中的一张表,Model 内的字段则对应表中的列。通过 Schema 定义 Model,可以完全摆脱手写 SQL 的建表方式。
Model 基础结构
schema.prisma
prisma
model User {
id Int @id @default(autoincrement())
name String
email String @unique
}Model 三大核心组成
字段(Fields)
定义表中的列,例如 id、name、email。
属性(Attributes)
如 @id、@unique、@default,用于约束字段行为。
关系(Relations)
用于连接多个 Model,例如 User ↔ Post。
字段类型(Scalar Types)
Prisma 常用数据类型
| 类型 | 说明 | 示例 |
|---|---|---|
| String | 字符串类型 | name String |
| Int | 整数 | age Int |
| Boolean | 布尔值 | isActive Boolean |
| DateTime | 时间类型 | createdAt DateTime |
| Float | 浮点数 | price Float |
| Json | JSON 数据 | metadata Json |
字段约束(Attributes)
常见字段装饰器
@id
定义主键字段。
@default
设置默认值,如 now()、autoincrement()。
@unique
字段唯一约束。
@updatedAt
记录数据更新时间(自动维护)。
schema.prisma
prisma
model User {
id Int @id @default(autoincrement())
name String
email String @unique
isActive Boolean @default(true)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}索引(Index)
索引用于提升查询性能,在 Prisma 中可以通过 @index 和 @@index 定义单列或组合索引。
schema.prisma
prisma
model User {
id Int @id @default(autoincrement())
email String
name String
@@index([email])
}复合索引(Composite Index)
schema.prisma
prisma
model Post {
id Int @id @default(autoincrement())
title String
userId Int
@@index([userId, title])
}Model 设计建议
最佳实践
避免冗余字段
不要存储可以计算出来的数据。
合理使用索引
只在高频查询字段上建立索引。
统一时间字段
建议统一使用 createdAt / updatedAt。
避免过宽 JSON
Json 类型虽然灵活,但不利于查询优化。
下一步学习
进入关系模型
一对一关系
User ↔ Profile
一对多关系
User ↔ Posts
相关笔记
在数字化一期,此笔记未产生更深相关的共鸣分枝。