Prisma 多对多关系:创建和连接

问题描述

在我的 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
        },},});

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

解决方法

您需要的是 connectOrCreate

所以这样的事情应该可行:

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

您还可以在文档 here

中阅读更多相关信息