首页  >  问答  >  正文

Prisma 中的字段“id”外键约束失败

model Renting_Units {
  id              Int               @id @default(autoincrement())
  name            String            @unique(map: "name") @db.VarChar(255)
  description     String?           @db.VarChar(255)
  createdAt       DateTime          @default(now()) @db.DateTime(0)
  updatedAt       DateTime          @default(now()) @db.DateTime(0)
  User            Users             @relation(fields: [id], references: [id])
  created_by      Int
  Renting_Periods Renting_Periods[]
}


model Renting_Periods {
  id            Int           @id @default(autoincrement())
  product_id    Int           @db.Int
  Products      Products      @relation(fields: [product_id], references: [id], onUpdate: Cascade, onDelete: Cascade)
  start_date    DateTime      @db.DateTime(0)
  end_date      DateTime      @db.DateTime(0)
  createdAt     DateTime      @default(now()) @db.DateTime(0)
  updatedAt     DateTime      @default(now()) @db.DateTime(0)
  renting_unit  Int           @db.Int
  Renting_Units Renting_Units @relation(fields: [renting_unit], references: [id], onUpdate: Cascade, onDelete: Cascade)
  User          Users         @relation(fields: [id], references: [id])
  created_by    Int
  Invoices      Invoices[]
}

我收到外键 ID 错误。 我添加了一些租赁期,创建更多后出现此错误,但 ID 是自动递增的。 我尝试了网上的不同方法,但没有找到解决方案。 问题是它也发生过一次,但是我刷新了数据库,过了一段时间它又发生了。

我尝试插入新租赁期的代码:

await prisma.renting_Periods.create({
      data: {
        Products: {
          connect: {
            id: product_id,
          },
        },
        start_date,
        end_date,
        Renting_Units: {
          connect: {
            id: renting_unit_id,
          },
        },
        created_by: user_data.id,
      },
    });



The full erorr that displayed on the console:



→  74 await prisma.renting_Periods.create(
  Foreign key constraint failed on the field: `id`
    at RequestHandler.handleRequestError 
  clientVersion: '4.2.1',
  meta: { field_name: 'id' }

P粉023326773P粉023326773298 天前364

全部回复(1)我来回复

  • P粉041881924

    P粉0418819242023-12-27 09:23:24

    您正在尝试将 ProductRenting_Units 模型连接到 renting_Periods 模型,但您引用的 ID 并未引用ProductRenting_Units 模型。该 ID 可能指其他内容,但当您使用的 ID 对于您尝试执行的操作无效(在本例中连接 ProductRenting_Units )。

    回复
    0
  • 取消回复