postgresql 一对多关系不适用于Prisma

nuypyhwy  于 2023-01-02  发布在  PostgreSQL
关注(0)|答案(2)|浏览(211)

我正在使用Prisma w/ Postgres,并尝试与用户建立简单的一对多关系,该用户可以拥有零个或多个产品。我可以为特定用户创建1个产品,但当我尝试创建另一个产品时,我遇到了此错误:Invalid prisma.product.create()invocation: Unique constraint failed on the fields: ('userEmail').我肯定遗漏了一些东西,但可能需要另一双眼睛来关注它。
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路径,我可以通过POST为用户创建新产品

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: "xxx@x.com" // 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 })
};
r3i60tvu

r3i60tvu1#

愚蠢的错误。我所需要做的就是从Product模型上的userEmail中删除@unique

elcex8rz

elcex8rz2#

不需要将product表中的外键userEmail定义为@uniuqe

相关问题