How to use Prisma model type in tRPC mutation w/ Zod
I have some models defined in my schema.prisma file. Let's say they look like this:
I am using a tRPC mutation to create an "Art" in my Planetscale database. So, since I'm using Zod, I am doing something like this:
I know I can get the Creator type from Prisma, but I don't know how to tell Zod to expect those properties as the input so that the tRPC procedure will run. I hope I'm explaining this ok because it's kinda hard to put into words lol
4 Replies
You can nest objects in zod like:
.input(
z.object({
art: z.object({
id:z.string(),
}),
creators: z.object({
id: z.string(),
//...like that
})
})
)
Ok just gave this a try but TS still throwing a Type error. Here's what it's saying:
Type '{ collaboratorId: string; songId: string; }[]' is not assignable to type 'CreatorUncheckedCreateNestedManyWithoutArtInput | CreatorCreateNestedManyWithoutArtInput | undefined'.ts(2322)
This is making me think that there should be a way to get the type called "CreatorCreateNestedManyWithoutArtInput" and use it. Also the type itself makes it sound like it's being created without Art input, even though it is? Idk honestly very confused by it all.
You need to define the creators object on the input and then use it when calling the mutation property as you are doing. Try for example:
If I'm not wrong that is what your Prisma Schema is expecting
It is the same @peterkyle01 is saying
Ok I think I might've figured out what was going wrong - in the mutation I wasn't using the create property. So now in the input it reads:
And in the mutation it reads:
But I'm not including the relation field from the Prisma model in any way - is that necessary? Will it fill in automatically? About to test btw so will update shortly.