node prisma+postgreSQL中的查询与过滤

先建一个Prisma Schema,用于后面查询与过滤的数据操作

javascript 复制代码
model User {
  id        Int      @id @default(autoincrement())
  email     String   @unique
  name      String?
  createdAt DateTime @default(now())
  posts     Post[]
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  published Boolean  @default(false)
  views     Int      @default(0)
  createdAt DateTime @default(now())
  authorId  Int
  author    User     @relation(fields: [authorId], references: [id])

  categories Category[]
}

model Category {
  id    Int    @id @default(autoincrement())
  name  String @unique
  posts Post[]
}

some、every、none

在进行to-many操作时,任何支持where条件的prisma方法,都可以在针对关系字段的过滤中使用它们,比如:

findeMany()、findFirst()、update/updateMany()、delete/deleteMany()

javascript 复制代码
// ① some:至少有一篇已发布的文章
const usersWithAtLeastOnePublished = await prisma.user.findMany({
  where: {
    posts: {
      some: { published: true },
    },
  },
})

// ② every:所有文章都已发布(注意:没有任何文章的用户也会被匹配)
const usersAllPublished = await prisma.user.findMany({
  where: {
    posts: {
      every: { published: true },
    },
  },
})

// ③ none:没有任何已发布的文章
const usersWithNoPublished = await prisma.user.findMany({
  where: {
    posts: {
      none: { published: true },
    },
  },
})

过滤操作符

equals、not、in、notIn、lt、lte、gt、gte、contains、startsWith、endsWith、has、hasEvery、hasSome、isEmpty

复合条件

javascript 复制代码
{
  AND: [...],   // 所有条件都满足
  OR: [...],    // 任一条件满足
  NOT: {...},   // 条件不满足
}

一段代码示例:

javascript 复制代码
// AND(隐式):多个条件同时满足
const users1 = await prisma.user.findMany({
  where: {
    name: { not: null },
    posts: {
      some: { published: true },
    },
  },
})

// 显式 AND
const users2 = await prisma.user.findMany({
  where: {
    AND: [
      { name: { contains: 'a' } },
      { posts: { some: { views: { gt: 100 } } } },
    ],
  },
})

// OR:满足任意一个条件
const users3 = await prisma.user.findMany({
  where: {
    OR: [
      { email: { endsWith: '@example.com' } },
      { posts: { some: { published: true } } },
    ],
  },
})

// NOT:取反
const users4 = await prisma.user.findMany({
  where: {
    NOT: {
      posts: {
        some: { published: false },
      },
    },
  },
})

// 混合:AND + OR + NOT + 关系过滤
const users5 = await prisma.user.findMany({
  where: {
    AND: [
      { createdAt: { gte: new Date('2025-01-01') } },
      {
        OR: [
          { posts: { some: { views: { gt: 1000 } } } },
          { posts: { every: { published: true } } },
        ],
      },
      {
        NOT: { email: { endsWith: '@spam.com' } },
      },
    ],
  },
})

排序

javascript 复制代码
orderBy: { field: 'asc' }         // 单列升序
orderBy: { field: 'desc' }        // 单列降序
orderBy: [{ f1: 'asc' }, { f2: 'desc' }]  // 多列排序

总结示例

javascript 复制代码
const users = await prisma.user.findMany({
  where: {
    AND: [
      { name: { in: ['Alice', 'Bob', 'Charlie'] } },
      { posts: { some: { published: true } } },
    ],
  },
  orderBy: [
    { createdAt: 'desc' },
    { name: 'asc' },
  ],
  include: {
    posts: {
      where: { published: true },
      orderBy: { createdAt: 'desc' },
      take: 1,
    },
  },
})
相关推荐
木头左1 小时前
【Node.js】Markdown 转带图片 Word 文档实战:docx 库转换器设计与 5 个踩坑
node.js·word·markdown·文档自动化
思特奇时空智能1 小时前
大规模点要素地图渲染性能优化实践
vue.js·arcgis·性能优化·node.js·html·gis·webgl
w3296362712 天前
飞书接单到月度结算:我用一个 DSH 插件跑通鞋类采购 WMS,附 22 项验收
pdf·node.js·飞书·后端开发·ai agent
濮水大叔3 天前
Cabloy/Vona 为什么不需要 NestJS 的 Dynamic Module
typescript·node.js·nestjs
匠云创新3 天前
读完一万段要两分钟:我们把标书读取从 WPS 对象模型搬到了 docx 解析
性能优化·node.js
某哈压力大3 天前
SSH 突然 Connection reset?不是密钥坏了,是 OpenSSL 把 sshd 干趴了
前端·node.js·命令行
回眸&啤酒鸭3 天前
【回眸】Node.js 新手从零到一实战指南
node.js
浪遏3 天前
recruitment-cli:让 AI 接手求职招聘,从架构到一次发送超时
架构·typescript·node.js
沉默小管5 天前
我用 NestJS + Nuxt 3 做了个导航站,聊几个踩过的坑
node.js·seo
非优秀程序员6 天前
第02章 杭电的英语老师与一台服务器|《互联网产品恩仇录》
数据库·node.js·代码规范