node.jsdatabaseormprismaprisma2

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


How can I assign some tags to the post using Prisma.js?

I have some tags already and I want to assign some tags to the post? I don't want to create a new tag.

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
}

In the Prisma website, there is an example but it's suitable for creating some tags and assign them to the Post. While I want to add some of the existing tags to the article.

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


Solution

  • I have used $transaction and in this transaction I created 2 insert command also I have defined an Id for post with uuid package. postId = v4() . v4() is a function in uuid that generates a unique 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;
      }