I'd like to set up my models with an optional rela...
# orm-help
g
I'd like to set up my models with an optional relation. This is what my
schema.prisma
file looks like:
Copy code
model User {
  idStr String @id 
  name String?
  statuses Status[]
}

model Status {
  idStr String @id
  createdAt DateTime
  userIdStr String
  user User? @relation(fields: [userIdStr], references: [idStr])
}
But I get this error:
Copy code
Foreign key constraint failed on the field: `Status_userIdStr_fkey (index)`
when I try to create a status that has a
userIdStr
for which there is no corresponding
User
. How do I set up my models such that there doesn't have to be a
User
present for a given
Status.userIdStr
?
h
Looks like
userIdStr
to be optional
m
sup gabe!
👋 1
r
You need
userIdStr
to be optional as well:
Copy code
model Status {
  idStr String @id
  createdAt DateTime
  userIdStr? String
  user User? @relation(fields: [userIdStr], references: [idStr])
}
g
hey @Mo El!
@Ryan / @Hyo - I get that this will avoid the error, but it is not an optional field in the model because every status has a
userIdStr
it's just that for some of these statuses there is no corresponding
User
record. Is it not possible to set up my schema to allow this type of relation?
r
If every Status has a
userIdStr
, then every Status will also have a
User
. It’s not an either/or, the foreign key
userIdStr
is always mapped to the virtual field
User
. So if you know that
userIdStr
will always be present, remove the
?
from both.