search

Home  >  Q&A  >  body text

Foreign key constraint fails on field 'id' in Prisma

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[]
}

I'm getting a foreign key ID error. I added some lease periods and after creating more I get this error but the IDs are auto-incremented. I tried different methods online but didn't find a solution. The problem is that it happened once too, but I refreshed the database and after some time it happened again.

I try to insert the code for the new lease period:

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粉023326773340 days ago413

reply all(1)I'll reply

  • P粉041881924

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

    You are trying to connect the Product or Renting_Units model to the renting_Periods model, but the ID you are referencing does not reference the Product or Renting_Units Model. The ID may refer to something else, but when you use an ID that is not valid for the operation you are trying to perform (in this case concatenating Product or Renting_Units ).

    reply
    0
  • Cancelreply