什么是一对多关系?
一对多关系(One-to-Many)指一个父模型对应多个子模型。例如:一个用户可以发布多篇文章,一个分类可以包含多个商品。在 Prisma 中,一对多关系通常通过外键字段来实现。
常见一对多场景
用户 ↔ 文章
User -> Posts
分类 ↔ 商品
Category -> Products
订单 ↔ 订单项
Order -> OrderItems
博客 ↔ 评论
Post -> Comments
Prisma 一对多关系定义
在 Prisma 中,一对多关系由一方引用多方,多方保存外键字段。Prisma 会通过 @relation 自动识别关系结构。
schema.prisma
prisma
model User {
id Int @id @default(autoincrement())
name String
posts Post[]
}
model Post {
id Int @id @default(autoincrement())
title String
userId Int
user User @relation(fields: [userId], references: [id])
}关系结构解析
关键字段说明
posts Post[]
表示一个 User 拥有多个 Post
userId
外键字段,指向 User 表
@relation
定义外键关联关系
references
指定关联字段(通常是 id)
数据插入示例
create.ts
typescript
await prisma.user.create({
data: {
name: "John",
posts: {
create: [
{ title: "Post 1" },
{ title: "Post 2" }
]
}
}
});查询一对多关系
query.ts
typescript
const users = await prisma.user.findMany({
include: {
posts: true
}
});query-filter.ts
typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: {
where: { title: { contains: "Prisma" } }
}
}
});性能优化建议
最佳实践
避免全量 include
不要在列表查询中无限加载子表数据。
分页子数据
对子表数据使用 skip / take 控制数量。
索引外键字段
userId 必须加索引提高查询速度。
避免深层嵌套
超过 2 层 include 会严重影响性能。
常见错误
schema.prisma
prisma
model Post {
id Int @id @default(autoincrement())
title String
user User @relation(fields: [userId], references: [id]) // ❌ userId 未定义
}一对多关系中必须在多的一方显式定义外键字段,否则 Prisma 会报错或无法正确生成关系。
下一步学习
进入下一阶段
多对多关系
User ↔ Roles
CRUD 操作
Prisma Client 核心使用
相关笔记
在数字化一期,此笔记未产生更深相关的共鸣分枝。