【问题标题】:How to use connectOrCreate with many to many in prisma如何在 prisma 中使用 connectOrCreate 与多对多
【发布时间】:2021-10-22 17:14:59
【问题描述】:

我想用Prisma把文章和标签关联起来,即:一个帖子有多个标签,一个标签属于多个帖子
但是 Prisma 中的示例会导致创建重复标签

这是我的 Prisma 模型

model Article {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  title     String
  summary   String
  link      String   @unique
  archive   String
  content   String
  image     String
  tags      Tag[]
}

model Tag {
  id       Int       @id @default(autoincrement())
  name     String
  articles Article[]
}

根据文档,这是我的代码,它会导致出现重复的标签

await prisma.article.create({
  data: {
    title,
    summary,
    link,
    archive,
    content,
    image,
    tags: {
      create: tags.map((tag) => ({ name: tag })),
    },
  },
});

我使用connectOrCreate时,多对多模式报错

await prisma.article.create({
  data: {
    title,
    summary,
    link,
    archive,
    content,
    image,
    tags: {
      connectOrCreate: {
        where: tags.map((tag) => ({ name: tag })),
        create: tags.map((tag) => ({ name: tag })), 
      },
    },
  },
});

【问题讨论】:

  • 在您的代码中使用tags.map((tag) => ({ name: tag })) 的原因是什么?

标签: database blogs prisma


【解决方案1】:

代码中有两个错误。

Tag.name 字段不唯一

根据我从您的域中推断,两个标签不应具有相同的名称。此外,由于name 字段不是唯一的,您不能单独使用它来唯一标识特定的Tag 记录,因此如果您尝试仅传递where 中的name 字段,Prisma 会报错connectOrCreate 的条件。

对此最简单且合乎逻辑的解决方案是使name 字段唯一。这是您更新的标签模型

model Tag {
  id       Int       @id @default(autoincrement())
  name     String    @unique  // change
  articles Article[]
}

connectOrCreate 的语法不正确

您将单独的数组传递给 wherecreate 字段。相反,当您想要连接/创建多条记录时,将一组对象传递给connectOrCreate,每个对象都有自己的wherecreate 字段。这是 Prisma Docs 中显示how to use connectOrCreate with multiple records 的示例。

您的创建查询应该是这样的:

await prisma.article.create({
  data: {
    title,
    summary,
    link,
    archive,
    content,
    image,
    tags: {
        connectOrCreate: tags.map((tag) => {
            return {
                where: { name: tag },
                create: { name: tag },
            };
        }),
    },
  },
});

【讨论】:

    猜你喜欢
    • 2021-02-28
    • 2022-01-27
    • 2021-12-04
    • 2022-01-27
    • 2021-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    相关资源
    最近更新 更多