Hey all, I'm using prisma with trpc, zod and nextj...
# orm-help
o
Hey all, I'm using prisma with trpc, zod and nextjs. I have 2 models on my prisma schema as such:
Copy code
model 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?
Copy code
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
?
1
h
Is 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 the
pollId
that the options belong to?
You can create an option alongside and it will automatically connect the record:
Copy code
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 a
voterToken
?
You can mark this field optional in your schema and it will allow you to omit this field while creating it for the first time:
Copy code
model Option {

  voterToken String? @db.VarChar(255)
  
}
v
👋 Hello @Omar, did you have a chance to check Harshit's answer? Let us know if you still have any questions!