skip to Main Content

I’m using Prisma w/ Postgres and am trying to have a simple 1-to-many relationship with a User which can have zero or more Product(s). I’m able to create 1 product for a particular user but when I try to create another product I’m met with this error: Invalid prisma.product.create() invocation: Unique constraint failed on the fields: ('userEmail'). I’m definitely missing something but probably need another pair of eyes on it.

schema.prisma

model Product {
  id              String   @id @default(cuid())
  createdAt       DateTime @default(now())
  updatedAt       DateTime @updatedAt
  name            String
  description     String?
  published       Boolean  @default(false)
  user            User     @relation(fields: [userEmail], references: [email])
  userEmail       String @unique
  productImageUrl String?
}

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  active        Boolean?
  products      Product[]
}

Next.js API route where I can POST to create new products for a user

const Index = async (_req: NextApiRequest, res: NextApiResponse) => {
  const reqBody = _req.body ?? null;

  if (!reqBody) res.status(200).json({ message: "No request body found" });
  const product = await prisma.product.create({
    data: {
      user: {
        connect: {
          email: "[email protected]" // this user already exists in the DB
        },
      },
      published: true,
      name: "Test Product 3",
      createdAt: new Date,
      updatedAt: new Date,
    }
  })
  res.status(200).json({ data: reqBody })
};

2

Answers


  1. Chosen as BEST ANSWER

    Silly mistake. All I needed to do was remove @unique from userEmail on the Product model.


  2. you don’t need to define foreign key userEmail in the product table as @uniuqe

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search