Prisma.js - 如何插入具有多对多关系的 table

Prisma.js - How to insert into table that has many-to-many relationship

如何使用 Prisma.js 为 post 分配一些标签?

我已经有一些标签了,我想为 post 分配一些标签? 我不想创建新标签。

schema.prisma:

model Post {
  Id                 String           @id @default(uuid())
  AuthorId           String
  Author             User             @relation(fields: [AuthorId], references: [Id])
  CategoryId         String?
  Category           Category?        @relation(fields: [CategoryId], references: [Id])
  Title              String           @db.VarChar(255)
  Description        String?          @db.MediumText
  Summary            String?          @db.VarChar(255)

  Tags               TagPostMapping[]
}

model TagPostMapping {
  Id           String     @id @default(uuid())
  Post         Post?      @relation(fields: [PostId], references: [Id])
  PostId       String?
  Tag          Tag?       @relation(fields: [TagId], references: [Id])
  TagId        String?
  CreatedDate  DateTime   @default(now())
  ModifiedDate DateTime?  @updatedAt
}

model Tag {
  Id             String           @id @default(uuid())
  Title          String           @unique
  Posts          TagPostMapping[]
  CreatedDate    DateTime         @default(now())
  ModifiedDate   DateTime?        @updatedAt
}

在 Prisma 网站上,有一个示例,但它适用于创建一些标签并将它们分配给 Post。 虽然我想在文章中添加一些现有的标签。

https://www.prisma.io/docs/support/help-articles/working-with-many-to-many-relations#explicit-relations

我使用了 $transaction,在这个事务中我创建了 2 个插入命令,我还为 post 和 uuid 包定义了一个 ID。 postId = v4()v4()uuid 中的一个函数,它生成一个唯一的 Id

  public async Create(post: IPost): Promise<Post> {

    let postId = v4();
    let postTagIds: postTagMapping[] = [];
    post.Tags?.map(tag => postTagIds.push({ PostId: postId, TagId: tag.Id }));

    const transResult = await ApplicationDbContext.Prisma.$transaction([
      ApplicationDbContext.Prisma.post.create({
        data: {
          Id: postId,
          Title: post.Title,
          Summary: post.Summary,
          Description: post.Description,
          IsActive: post.IsActive,
          IsPublished: post.IsPublished,
          IsActiveNewComment: post.IsActiveNewComment,
          AuthorId: post.AuthorId,
          CategoryId: post.CategoryId,
        },
      }),
      ApplicationDbContext.Prisma.tagPostMapping.createMany({
        data: postTagIds
      })

    ]).finally(async () => {
      await ApplicationDbContext.Prisma.$disconnect();
    });

    let result = transResult as unknown as Post;

    return result;
  }

我遇到过类似的情况,下面的代码对我有用:

  addTagToPost(addTagDto: AddTagDto): Promise<TagDto> {
    return prisma.tag.update({
      where: { Id: addTagDto.tagId },
      data: {
        Posts: {
          create: [
            {
              Post: {
                connect: {
                  Id: addTagDto.postId,
                },
              },
            },
          ],
        },
      },
    });
  }

PS: 由于PostTag有many-to-many关系,你也可以更新prisma.post.update