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

Prisma查询未设置字段及可选关联查询的方法疑问

Prisma 查询问题解答

一、查询可选标量字段未设置的记录

给定Schema:

model Person {
  id      String   @id @default(cuid())
  name    String
  email   String?
}

要查询name = "foo"且email未设置(即数据库中为null)的Person,三种写法的有效性如下:

  • 写法1(不可行):

    prisma.person.findMany({
      where: {
        name: "foo",
        email: undefined,
      }
    })
    

    Prisma会自动忽略where中的undefined字段,实际仅按name: "foo"查询,无法筛选出email未设置的记录。

  • 写法2(可行):

    prisma.person.findMany({
      where: {
        name: "foo",
        email: null,
      }
    })
    

    对于可选标量字段(如String?),直接指定email: null会生成email IS NULL的SQL,完全符合需求。

  • 写法3(可行):

    prisma.person.findMany({
      where: {
        name: "foo",
        email: { is: null },
      }
    })
    

    这是Prisma显式的空值查询语法,和写法2效果一致,生成的SQL语句完全相同。

二、可选关联的查询差异

给定包含可选关联的Schema:

model Person {
  id      String   @id @default(cuid())
  name    String
  pet     Pet?     @relation
}
model Pet {
  id      String   @id @default(cuid())
  name    String
  ownerId String?
  owner   Person?  @relation(fields: [ownerId], references: [id])
}

1. 查询名为"foo"且没有宠物的Person

需针对关联字段使用嵌套查询语法:

prisma.person.findMany({
  where: {
    name: "foo",
    pet: { is: null },
  }
})

注意:关联字段不支持直接写pet: null,必须用{ is: null }表示关联记录不存在。

2. 查询名为"foo"且没有主人的Pet

写法逻辑类似,但针对Pet模型的owner关联字段:

prisma.pet.findMany({
  where: {
    name: "foo",
    owner: { is: null },
  }
})

两者的区别

本质都是查询“关联记录不存在”的场景,但因涉及不同模型的关联字段,查询时指定的字段名(pet vs owner)不同。另外,Pet模型还可通过外键ownerId直接查询,效果和关联字段写法一致:

prisma.pet.findMany({
  where: {
    name: "foo",
    ownerId: null,
  }
})

而Person模型的pet关联未暴露外键字段,因此只能用关联字段的嵌套查询方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:21:38