Home > database >  1-to-Many relationship not working with Prisma
1-to-Many relationship not working with Prisma

Time:12-31

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 })
};

CodePudding user response:

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

CodePudding user response:

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

  • Related