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

Prisma Select触发TypeScript错误:tables属性不在BookingSelect中

问题:Prisma查询Booking模型时指定tables字段触发TypeScript错误

错误提示

Type '{ id: true; people: true; time: true; tables: true; user_id: true; }' is not assignable to type 'BookingSelect'.
  Object literal may only specify known properties, and 'tables' does not exist in type 'BookingSelect'.ts(2322)

相关代码

TypeScript 查询代码

const bookings = await prisma.booking.findMany({
  where: {
    time: {
      gte: new Date(`${dataParams.date}, ${searchTimes[0]}`),
      lte: new Date(
        `${dataParams.date}, ${searchTimes[searchTimes.length - 1]}`
      ),
    },
  },
  select: {
    id: true,
    people: true,
    time: true,
    tables: true,
    user_id: true,
  },
});

Prisma Schema 核心关联定义

model Booking {
  id               Int              @id @default(autoincrement())
  // 省略其他字段
  tables BookingOnTable[]
}

model Table {
  id             Int              @id @default(autoincrement())
  // 省略其他字段
  booking_on_table BookingOnTable[]
}

model BookingOnTable {
  booking_id Int
  booking    Booking @relation(fields: [booking_id], references: [id])
  table_id   Int
  table      Table   @relation(fields: [table_id], references: [id])
  created_at DateTime @default(now())
  updated_at DateTime @updatedAt

  @@id([booking_id, table_id])
}

错误原因及解决方案

原因1:未重新生成Prisma Client

修改Schema后,必须重新生成Prisma Client才能同步TypeScript类型定义。如果新增tables字段后未执行生成命令,Client类型中不会包含该字段,直接查询就会触发报错。

解决步骤:
运行命令更新Prisma Client:

npx prisma generate

原因2:手动多对多关联的反向关联未配置名称

由于你手动定义了多对多中间表BookingOnTable,需要为双向关联指定统一的@relation(name)属性,否则Prisma无法正确识别反向关联关系,导致生成的Client中缺失tables字段。

修正Schema:
为所有关联字段添加统一的关联名称:

  1. 修改Booking模型的tables字段:
tables BookingOnTable[] @relation(name: "BookingToBookingOnTable")
  1. 修改BookingOnTable模型的booking字段:
booking Booking @relation(fields: [booking_id], references: [id], name: "BookingToBookingOnTable")
  1. 修改Table模型的booking_on_table字段:
booking_on_table BookingOnTable[] @relation(name: "TableToBookingOnTable")
  1. 修改BookingOnTable模型的table字段:
table Table @relation(fields: [table_id], references: [id], name: "TableToBookingOnTable")

优化查询语句(可选)

如果需要获取关联的Table数据,不能直接写tables: true,需要嵌套select来指定具体要查询的中间表或关联表字段:

const bookings = await prisma.booking.findMany({
  where: {
    time: {
      gte: new Date(`${dataParams.date}, ${searchTimes[0]}`),
      lte: new Date(`${dataParams.date}, ${searchTimes[searchTimes.length - 1]}`),
    },
  },
  select: {
    id: true,
    people: true,
    time: true,
    user_id: true,
    // 获取中间表及关联的Table数据
    tables: {
      select: {
        table: {
          select: {
            id: true,
            restaurant_id: true,
          },
        },
        created_at: true,
      },
    },
  },
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:09:54