5

在我的 Prisma 模式中,帖子和类别之间存在多对多关系。我添加@map了匹配 Postgres snake_case 命名约定的选项:

model Post {
  id         Int            @id @default(autoincrement())
  title      String
  body       String?
  categories PostCategory[]

  @@map("post")
}

model Category {
  id    Int            @id @default(autoincrement())
  name  String
  posts PostCategory[]

  @@map("category")
}

model PostCategory {
  categoryId Int      @map("category_id")
  postId     Int      @map("post_id")
  category   Category @relation(fields: [categoryId], references: [id])
  post       Post     @relation(fields: [postId], references: [id])

  @@id([categoryId, postId])
  @@map("post_category")
}

我正在尝试同时创建具有多个类别的帖子。如果某个类别存在,我想connect将类别添加到帖子中。如果该类别不存在,我想创建它。创建部分运行良好,但连接部分存在问题:

  await prisma.post.create({
    data: {
      title: 'Hello',
      categories: {
        create: [{ category: { create: { name: 'News' } } }],
        connect: {
          categoryId_postId: { categoryId: 1, postId: ? }, // This doesn't work, even if I had the postId
        },
      },
    },
  });

如何使用我拥有的架构将现有类别连接到新帖子?

4

4 回答 4

10

你在这里需要的是connectOrCreate.

所以这样的事情应该有效:

      await prisma.post.create({
        data: {
          title: 'Hello',
          categories: {
            create: [
              {
                category: {
                  create: {
                    name: 'category-1',
                  },
                },
              },
              { category: { connect: { id: 10 } } },
            ],
          },
        },
      });

您还可以在此处的文档中阅读有关此内容的更多信息

于 2021-01-29T08:20:40.803 回答
2

这个问题把我逼到了墙角,所以我会在这里贡献我的解决方案,以防它帮助别人。首先,请阅读:https ://www.prisma.io/docs/concepts/components/prisma-schema/relations/many-to-many-relations

我的架构与所讨论的架构相似,唯一的区别是我有文件而不是帖子和标签而不是类别。要将创建的文件的标签链接到现有标签,我使用了这个:

  await Promise.all(DEFAULT_FILES[2].map(file => prisma.file.create({
    data: {
      ...file,
      user_id: userId,
      parent_id: homeFolder.id,
      tags: {
        create: file.tags?.map(name => ({
          tag: {
            connect: {
              id: tags.find(t => t.name === name)?.id
            }
          }
        }))
      },
    }
  })))
于 2021-10-20T14:20:56.613 回答
0

显式多对多创建/更新现有标签在此处阅读更多

let args =[1,2,3,4]
tags: {
      create: args.tags?.map(tagId=>({
          tag:{
              connect:{
                  id:tagId
              }
          }
      }))
    },
 }

于 2022-02-13T18:08:29.063 回答
0
await prisma.postCategory.create({
  data: {
    category: {
      connectOrCreate: {
        id: categoryId
      }
    },
    posts: {
      create: [
        {
          title: 'g3xxxxxxx',
          body: 'body g3xxxxx'
        }
      ],
    },
  },
})

您应该连接到现有记录,然后创建要与第一个记录相关的记录。

https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries(连接现有记录)

于 2022-01-10T15:08:19.253 回答