PrismaP
Prisma2mo ago
8 replies
Imprevisible

zero-to-one relationship

Hi everyone, I'm trying to do a zero-to-one relationship in Prisma, but sadly it's not working:

model Assignment {
  id        String    @id @default(uuid())
  startDate DateTime?
  endDate   DateTime?

  resource      Resource @relation(fields: [resourceId], references: [externalId])
  resourceId    String

  originLocation      Location? @relation(fields: [originLocationId], references: [locationCode], name: "OriginLocation")
  originLocationId    String? 
  
  destinationLocation Location? @relation(fields: [destinationLocationId], references: [locationCode], name: "DestinationLocation")
  destinationLocationId String?
}


but I'm getting that error:

Invalid `this.prisma.assignment.create()` invocation in
/app/backend/dist/src/modules/stream/topics/resource/resource.service.js:107:43

  104         throw new Error(`The destination location ${objAssignment.locationCode} does not exist`);
  105     }
  106 }
→ 107 await this.prisma.assignment.create(
Foreign key constraint violated on the constraint: `Assignment_destinationLocationId_fkey


I'm setting destinationLocationId to either an existing id in the db, or a null value.

I guess it's not possible as I didn't saw any example in the documentation, but I'm hoping someone can help me.

Here's the code:

await this.prisma.assignment.create({
  data: {
    resourceId: resource.externalId,
    startDate: formatToDatabaseDate(
      payload.interval?.startInclusive
    ),
    endDate: formatToDatabaseDate(
      payload.interval?.endExclusive
    ),
    originLocationId: payload.sourceEntityCode || null,
    destinationLocationId: payload.targetEntityCode || null,
  },
});


FYI: either sourceEntityCode is an existing id (for sure), or it's null
FYI2: same for targetEntityCode
Was this page helpful?