select vs include 是什么?
在 Prisma 中,select 用于选择返回字段,而 include 用于加载关联数据。两者不能同时使用,是控制查询结构的核心机制。
核心区别
select
控制返回字段(精确字段控制)
include
加载关联模型数据
include: 加载关联数据
include.ts
typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
include: {
posts: true
}
});include 会返回完整关联模型数据,适合需要完整子数据的场景,例如用户详情页、文章详情页等。
select: 精确控制字段
select.ts
typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
select: {
id: true,
name: true
}
});select 用于只返回必要字段,可以显著减少数据传输量,是接口优化的关键手段。
嵌套 select + include
nested.ts
typescript
const user = await prisma.user.findUnique({
where: { id: 1 },
select: {
id: true,
name: true,
posts: {
select: {
id: true,
title: true
}
}
}
});为什么不能同时使用?
error.ts
typescript
// ❌ Prisma 会报错
await prisma.user.findMany({
select: { id: true },
include: { posts: true }
});select 决定返回结构,include 决定关联加载,两者逻辑冲突,因此 Prisma 不允许同时使用。
性能影响
性能对比
include
可能返回冗余数据,适合详情页
select
最小化数据返回,适合列表接口
实际开发建议
最佳实践
列表用 select
避免加载多余字段
详情用 include
完整展示关联数据
避免深层嵌套
超过 2 层 include 会影响性能
统一 DTO 输出
前后端字段结构保持一致
下一步学习
进入查询核心
where 条件查询
复杂过滤逻辑
分页与排序
skip / take / cursor
相关笔记
在数字化一期,此笔记未产生更深相关的共鸣分枝。