Search code examples
reactjstypescriptprismasupabasetrpc

Invalid `prisma.dayEvent.create()` invocation: Null constraint violation on the fields: (`id`)


When I'm trying to create event in calendar this error throws:

Invalid `prisma.dayEvent.create()` invocation:

Null constraint violation on the fields: (`id`)

Which is weird cause id have default() in prisma schema

Prisma schema:

model Calendar {
  id           String      @id @default(cuid())
  calendarName String
  dayEvents    dayEvent[]
  hostId       String

  host User @relation(fields: [hostId], references: [id])
}

model dayEvent {
  id         String   @id @default(cuid())
  name       String
  date       DateTime
  calendarId String

  calendar   Calendar @relation(fields: [calendarId], references: [id])
}

TRPC code where is prisma.create() triggering error:

create: protectedProcedure
    .input(
      z.object({ name: z.string(), date: z.date(), calendarId: z.string() })
    )
    .mutation(async ({ ctx, input }) => {
      return ctx.prisma.dayEvent.create({ //Error here
        data: {
          name: input.name,
          date: input.date,
          calendarId: input.calendarId,
        },
      })
    }),

In Calendar @id @default(cuid()) is working, I can create calendars. But for some reason in dayEvent it wants id. When I give it id, like that:

create: protectedProcedure
    .input(
      z.object({ name: z.string(), date: z.date(), calendarId: z.string() })
    )
    .mutation(async ({ ctx, input }) => {
      return ctx.prisma.dayEvent.create({
        data: {
          id: '1',
          name: input.name,
          date: input.date,
          calendarId: input.calendarId,
        },
      })
    }),

Everything is working as expected. Despite this, I don't think it will be right to generate ids like that with trpc.

Using full t3 stack

I searched on the web, but didn't find anything helpful. Did npx prisma db push to make sure database is in sync with the Prisma schema.


Solution

  • I think that the problem is on the schema.

    This is the docs example in the one to many relation:

    model User {
      id    Int    @id @default(autoincrement())
      posts Post[]
    }
    
    model Post {
      id       Int  @id @default(autoincrement())
      author   User @relation(fields: [authorId], references: [id])
      authorId Int
    }
    

    If you have a one to many relation: The problem in your code is here:

    calendar   Calendar @relation(fields: [id], references: [id])
    

    You should change fields [id] to fields [calendarId].

    In the Calendar you should change the day DayEvent to days DayEvent[]

    But if you have one to one relation this field should be @unique in the schema.

    I hope it helps you!