zod foreign key validation

This is probably a question that has been answered to death but I can't find anything that really helps so apologies if that's the case I'm trying to validate a create mutation for a album table and I want to have a field that specifies the episode id foreign key that the album is discussed in Getting the error 'Type 'string' has no properties in common with type 'MainEpisodeCreateNestedOneWithoutAlbumsInput'.' Prisma schema looks something like this (cut out all the unnecessary stuff):
model MainEpisode {
id String @id @default(cuid())
name String
albums Album[]
}

model Album {
id String @id @default(cuid())
name String
mainEpisodeId String
mainEpisode MainEpisode @relation(fields: [mainEpisodeId], references: [id])
}
model MainEpisode {
id String @id @default(cuid())
name String
albums Album[]
}

model Album {
id String @id @default(cuid())
name String
mainEpisodeId String
mainEpisode MainEpisode @relation(fields: [mainEpisodeId], references: [id])
}
Is there a way, other than just calling the id a string, that I can specify the shape of the foreign key?
3 Replies
hyhy
hyhyOP2y ago
I've found you can add additional formatting to the string with
mainEpisode: z.string().cuid()
mainEpisode: z.string().cuid()
but still not sure what the
MainEpisodeCreateNestedOneWithoutAlbumsInput
MainEpisodeCreateNestedOneWithoutAlbumsInput
type is or why it doesn't overlap with string
bennettdev
bennettdev2y ago
With Prisma, referencing "foreign" stuff is either done via the "ID" field (in your case mainEpisodeId) or via the "object" field (in your case mainEpisode). When using the "ID" field, you're supposed to give the string value. When using the "object" field, you're supposed to use the connect API, something like:
data: {
mainEpisode: {
connect: { id: input.yourStringId }
},
},
data: {
mainEpisode: {
connect: { id: input.yourStringId }
},
},
I would highly advise to not mix them. So in your example, the router's input should really be mainEpisodeId instead of mainEpisode. With that, you can either connect implicitly via the ID field or the object field (via connect). I tend to use the connect API more then the ID field, as the connect will throw an error if the ID you're trying to use one that does not exist.
hyhy
hyhyOP2y ago
Thanks for the explanation, will change my approach
Want results from more Discord servers?
Add your server