where 是 Prisma 的核心能力
where 用于过滤数据,是 Prisma 查询系统中最重要的部分。几乎所有复杂业务逻辑都依赖 where 条件组合实现。
常见查询能力
基础过滤
等于、不等于
模糊查询
contains / startsWith / endsWith
范围查询
gt / lt / gte / lte
逻辑组合
AND / OR / NOT
基础 where 查询
basic.ts
typescript
const users = await prisma.user.findMany({
where: {
name: "Alice"
}
});模糊查询(非常常用)
like.ts
typescript
const posts = await prisma.post.findMany({
where: {
title: {
contains: "Prisma"
}
}
});prefix.ts
typescript
await prisma.user.findMany({
where: {
email: {
startsWith: "admin"
}
}
});范围查询(数字 / 时间)
range.ts
typescript
const products = await prisma.product.findMany({
where: {
price: {
gte: 100,
lte: 500
}
}
});date.ts
typescript
const posts = await prisma.post.findMany({
where: {
createdAt: {
gte: new Date("2025-01-01"),
lte: new Date("2025-12-31")
}
}
});逻辑组合查询(核心能力)
logic.ts
typescript
const users = await prisma.user.findMany({
where: {
AND: [
{ name: { contains: "John" } },
{ email: { startsWith: "admin" } }
]
}
});
const posts = await prisma.post.findMany({
where: {
OR: [
{ title: { contains: "AI" } },
{ title: { contains: "Prisma" } }
]
}
});嵌套关系查询
relation.ts
typescript
const users = await prisma.user.findMany({
where: {
posts: {
some: {
title: {
contains: "Prisma"
}
}
}
}
});some 表示“至少一个满足条件”,还支持 none / every 等高级过滤方式。
advanced-relation.ts
typescript
const users = await prisma.user.findMany({
where: {
posts: {
none: {
title: { contains: "spam" }
}
}
}
});常见业务场景
实际应用
搜索功能
标题 / 内容模糊搜索
筛选列表
价格 / 时间 / 状态过滤
权限过滤
角色 / 用户状态控制
推荐系统
标签 + 行为过滤
性能注意事项
优化建议
避免深层嵌套 where
会显著影响查询性能
关键字段加索引
如 email / userId / createdAt
分页过滤结合
避免一次性拉取大量数据
拆分复杂查询
service 层做逻辑拆分
下一步学习
进入查询进阶
分页与排序
skip / take / cursor
事务处理
transaction / atomic query
相关笔记
在数字化一期,此笔记未产生更深相关的共鸣分枝。