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

如何在Prisma ORM中实现A与B关联的内连接查询?

使用Prisma ORM查询关联了A的B及其对应A数据

假设有一对多关系的模型A和B(B包含指向A的外键),要实现类似SQL内连接的效果——只获取已关联A的B,同时带出对应的A数据,可以按以下方式操作:

1. 确认Prisma Schema定义

首先确保你的schema正确关联两个模型,示例如下:

model A {
  id    Int     @id @default(autoincrement())
  name  String?
  Bs    B[]     // A对应多个B的关联字段
}

model B {
  id    Int     @id @default(autoincrement())
  aId   Int?    // 指向A的外键,允许为空(即存在未关联A的B)
  A     A?      @relation(fields: [aId], references: [id])
  // B的其他业务字段
}

2. 编写查询语句

要排除未关联A的B(即aId为null的记录),同时关联查询对应的A数据,直接用findMany配合where过滤和include关联即可:

// 使用Prisma Client执行查询
const linkedBWithA = await prisma.b.findMany({
  where: {
    aId: { not: null } // 过滤掉未关联A的B
  },
  include: {
    A: true // 同时查询对应的A完整数据
  }
});

如果只需要指定字段而非全量查询,可以用select替代include:

const linkedBWithA = await prisma.b.findMany({
  where: {
    aId: { not: null }
  },
  select: {
    id: true,
    // 按需指定B的其他字段
    A: {
      select: {
        id: true,
        name: true
        // 按需指定A的其他字段
      }
    }
  }
});

3. 优化:强制B必须关联A

如果业务上要求B必须关联A(不允许存在未关联的B),可以将B模型的aId设为非空字段,这样就不需要额外的where过滤:

model B {
  id    Int     @id @default(autoincrement())
  aId   Int     // 改为非空外键,强制B必须关联A
  A     A       @relation(fields: [aId], references: [id])
  // B的其他业务字段
}

此时查询简化为:

const allBWithA = await prisma.b.findMany({
  include: {
    A: true
  }
});

以上写法完全等价于你给出的SQL内连接语句,只会返回已关联A的B及其对应的A数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:05:23