2

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

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

架构.棱镜:

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

4

2 回答 2

1

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

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

PS:由于PostTag多对多的关系,你也可以更新prisma.post.update

于 2022-01-29T11:36:30.643 回答
-3

我已经使用$transaction并在此事务中创建了 2 个插入命令,还为带有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;
  }
于 2021-06-24T20:05:04.590 回答