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,
    },
  },
})
相关推荐
MasonYyp1 天前
安装npm依赖仓库Verdaccio
前端·npm·node.js
编程的一拳超人2 天前
【元宝搜索开发者征文大赛】四语实战:Java/Python/Go/Node.js 构建 AI 搜索应用全攻略
java·python·golang·node.js·agent
lucas_AI2 天前
今年 2 月就修好的漏洞,10 月才炸:HTTP2Shell 把 Node、Python 一锅端
node.js
SEO_juper3 天前
Node.js 全站死链检测工具:从 sitemap 出发一次找全 404
开发语言·人工智能·python·node.js·seo·外贸独立站
孟陬4 天前
解决动态 import 类型 Any 痼癖
typescript·node.js·bun
Dumbness4 天前
后台管理员把自己锁在门外:RBAC 里「自己的权限只能由别人来减」
安全·node.js
攻城狮白玉4 天前
Node.js 发布紧急安全更新:10 个漏洞,8 枚危险证书被拉黑。附AI修复提示词
node.js
Json____5 天前
用 FastAPI + Vue3 打造一套完整的在线考试系统:从组卷到阅卷的业务闭环实践
后端·node.js·fastapi·it学习·wwwoop.com
Dumbness5 天前
写 MCP 服务器踩的坑:stdout 是协议通道,一行不带换行的日志就能让客户端超时
node.js·mcp
flash俊杰5 天前
ContentPart 联合类型实战:不碰存量消息,怎么给 ChatMessage 加图片
node.js