精确筛选
查找名为 “John” 的用户
prisma.user.findMany({
where: {
name: 'John'
}
});
模糊筛选 contains
查找邮箱地址包含 “example.com” 的用户
where: {
email: {
contains: 'example.com'
}
}
忽略大小写 insensitive
where: {
name: {
contains: 'john',
mode: 'insensitive'
}
}
范围筛选
指定数组 in
查找 id 为 1、2 或 3 的用户
where: {
id: {
in: [1, 2, 3]
}
}
比较 gt 等
gt(大于)、gte(大于等于)、lt(小于)、lte(小于等于)
- 查找年龄大于 18 岁的用户
where: { age: { gt: 18 } }
数组匹配查询 has
tags 字段是字符串数组类型
where: {
tags: {
has: 'discount' // 查找包含 'discount' 标签的产品
}
}
多条件筛选
且
查找年龄大于 18 岁且名字为 “John” 的用户
where: {
age: {
gt: 18
},
name: 'John'
}
或 OR
查找名字为 “John” 或者年龄大于 18 岁的用户
where: {
OR: [
{ name: 'John' },
{ age: { gt: 18 } }
]
}
非 NOT
查找名字不是 “John” 的用户
where: {
NOT: {
name: 'John'
}
}
关联模型查询 some
查找发表过标题包含 “Prisma” 的文章的用户
where: {
posts: {
some: {
title: {
contains: 'Prisma'
}
}
}
}
- some 表示至少有一个关联的 Post 记录满足条件,你还可以使用 every(所有关联记录都满足条件)和 none(没有关联记录满足条件)等操作符。
实战范例
日期范围查询
const start = new Date('2024-01-01');
const end = new Date('2024-12-31');
const events = await prisma.event.findMany({
where: {
startDate: {
gte: start,
lte: end
}
}
});