Omar
09/11/2022, 6:44 AMmodel Poll {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
text String
endsAt DateTime?
ownerToken String @db.VarChar(255)
options Option[]
}
model Option {
id String @id @default(cuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
text String
votes Int @default(0)
voterToken String @db.VarChar(255)
poll Poll @relation(fields: [pollId], references: [id])
pollId String
}
I'd like to be able to create a poll with the associated options to it but having a hard time maybe with my lack of understanding. How can I create the options mutation? where do I get the poll id from if we haven't created it yet and same goes for the voter token?
export const pollRouter = createRouter().mutation("create", { //>>>> is this validator right?
input: z.object({
text: z.string().min(5).max(600),
options: z
.array(z.object({ text: z.string().min(2).max(500) }))
.min(2)
.max(5),
endsAt: z.string(),
},
async resolve({ input, ctx }) {
if (!ctx.token) throw new Error("Unauthorized");
return await prisma.poll.create({
data: {
text: input.text,
ownerToken: ctx.token,
endsAt: input.endsAt,
options: { // I am stuck here on how to create the options
create: await prisma.option.create({
data: {
text: input.text,
voterToken: ctx.token,
poll:
}
})
},
},
include: {
options: true,
},
});
},
});
• Is my validation correct?
• Where do I get the pollId
that the options belong to?
• How do I get the mutation to go through if initially I don't have a voterToken
?Harshit
09/12/2022, 9:51 AMIs my validation correct?Validation looks correct to me. It depends on your use case so adjust the parameters according to your use case.
Where do I get theYou can create an option alongside and it will automatically connect the record:that the options belong to?pollId
return await prisma.poll.create({
data: {
text: input.text,
ownerToken: ctx.token,
endsAt: input.endsAt,
options: {
create: {
text: input.text,
voterToken: ctx.token,
},
},
},
include: {
options: true,
},
});
How do I get the mutation to go through if initially I don’t have aYou can mark this field optional in your schema and it will allow you to omit this field while creating it for the first time:?voterToken
model Option {
voterToken String? @db.VarChar(255)
}
Vladi Stevanovic