【问题标题】:1-to-Many relationship not working with Prisma一对多关系不适用于 Prisma
【发布时间】:2022-12-31 10:31:08
【问题描述】:

我正在使用带 Postgres 的 Prisma,并尝试与可以具有零个或多个产品的用户建立简单的一对多关系。我可以为特定用户创建 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 })
};

【问题讨论】:

    标签: postgresql next.js prisma


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-06-30
      • 2018-02-03
      • 1970-01-01
      • 2022-10-25
      • 2021-10-03
      • 2021-07-23
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多