You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Prisma查询OR语句失效:无法正确筛选指定条件的Post数据

问题:Prisma查询未正确过滤Post,OR条件失效

需要查询满足以下任一条件的Post:

  • 所属Space的types包含PUBLIC
  • 当前userId是该Post所属Space的成员

但当前执行的查询会返回所有Post,OR语句完全不起作用。

用户查询代码

const posts = await prisma.post.findMany({
    where: {
        space: {
            OR: [
                {
                    members: {
                        some: {
                            userId,
                        }
                    },
                },
                {
                    types: {
                        has: "PUBLIC",
                    }
                },
            ],
        },
    },
});

Schema定义

model Post {
    id                     String                      @id @default(uuid())
    user                   User                        @relation(fields: [userId], references: [id], onDelete: Cascade)
    userId                 Int
    space                  Space?                      @relation(fields: [spaceId], references: [id], onDelete: Cascade)
    spaceId                Int?
}

model Space {
    id           Int           @id @default(autoincrement())
    members      SpaceMember[]
    types        SpaceType[]   @default([PUBLIC])
}

model SpaceMember {
    createdAt      DateTime           @default(now())
    user           User               @relation(fields: [userId], references: [id], onDelete: Cascade)
    userId         Int
    space          Space              @relation(fields: [spaceId], references: [id], onDelete: Cascade)
    spaceId        Int

    @@id([userId, spaceId])
}

enum SpaceType {
    PUBLIC //defaults to PUBLIC, lack of PUBLIC means it is PRIVATE
}

解决方案

问题根源:Post的space字段是可选类型(Space?),当Post没有关联任何Space时,space值为null。此时Prisma会将space: { OR: [...] }的条件判定为true,导致所有无Space关联的Post都被返回,最终看起来OR条件完全失效。

方案1:仅保留有Space关联且满足条件的Post

如果业务需求是只处理关联了Space的Post,直接在space条件里添加isNot: null:

const posts = await prisma.post.findMany({
  where: {
    space: {
      isNot: null,
      OR: [
        {
          members: {
            some: { userId }
          }
        },
        {
          types: { has: "PUBLIC" }
        }
      ]
    }
  }
});

方案2:按需处理无Space关联的Post

如果需要包含无Space的Post,需明确定义这类Post的过滤规则(比如是否允许返回),将条件拆到外层OR中:

const posts = await prisma.post.findMany({
  where: {
    OR: [
      // 关联了Space且满足任一条件
      {
        space: {
          OR: [
            { members: { some: { userId } } },
            { types: { has: "PUBLIC" } }
          ]
        }
      },
      // 无Space关联的Post,根据业务需求决定是否保留此分支
      { space: null }
    ]
  }
});

额外说明:Schema中Space的types默认值为[PUBLIC],新建Space默认是公开状态;若为私有Space,types数组中不会包含PUBLIC值,此逻辑无需调整。

内容的提问来源于stack exchange,提问作者rockets4all

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 19:57:31