【问题标题】:How to save many-to-many relation in typeorm?如何在typeorm中保存多对多关系?
【发布时间】:2021-10-18 08:29:19
【问题描述】:

我正在尝试在 PostsHashtags 之间建立关系,这是我的两个实体,

@Entity('posts')
export class Posts {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ length: 200, nullable: true })
  caption: string;

  @ManyToMany(() => Hashtags, (hashtags) => hashtags.posts, { eager: true })
  @JoinTable({ name: 'posts_hashtags_relation' })
  hashtags: Hashtags[];

  @ManyToOne(() => User)
  @JoinColumn({ name: 'author_id' })
  author: User;
}


@Entity('hashtags')
export class Hashtags {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column()
  hashtag: string;

  @ManyToMany(() => Posts, (post) => post.hashtags, {
    eager: false,
    cascade: true,
  })
  posts: Posts[];

  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date;
}

通过这些,typeorm 创建了一个数据库posts_hashtags_relation,其中包含postsIdhashtagsId 列 我在主题标签表中保存主题标签的服务是这样的

async createPost(creator : User, body: CreatePostDto) {
    if (!body.caption) {
      throw new BadRequestException('Post must contain some text');
    }

    // Extract hashtags from the post caption body
    const hashtags = body.caption.match(/\#\w+/g); // hashtags are the array of all hashtags in the post caption

    if(hashtags){
      for (const hashtag of hashtags) {
        const hashtagEntity = await this.hashtagRepo.findOne({ hashtag });
        if (!hashtagEntity) {
          await this.hashtagRepo.save({ hashtag });
        }
      }
    }
    
    const post = new Posts();
    post.author = creator;
    post.caption = body.caption;
    post.images = body.images;

    const resPost = await this.postsRepo.save(post);

    return resPost;
  }

但是如何保存posts_hashtags_relation表中的关系呢?

【问题讨论】:

    标签: database orm nestjs typeorm


    【解决方案1】:

    正如您在post 实体中注意到的那样,您在Hashtags 中拥有hashtags: Hashtags[]; 列...

    因此您可以将关系的数据保存在两个实体中:
    使用您的代码,我们可以做到:

    ...
    let hashtagsEntites:Array<Hashtags> = [];
    if(hashtags){
      for (const hashtag of hashtags) {
        var hashtagEntity = await this.hashtagRepo.findOne({ hashtag });
        if (!hashtagEntity) {
         hashtagEntity =  await this.hashtagRepo.save({ hashtag });
        }
        hashtagsEntites.push(hashtagEntity);
      }
    }
    
    const post = new Posts();
    post.author = creator;
    post.caption = body.caption;
    post.images = body.images;
    
    post.hashtags= hashtagsEntites  ; // here's how we save hashtags's post in the table 'posts_hashtags_relation'  
    const resPost = await this.postsRepo.save(post);
    

    【讨论】:

    • 是的,这行得通。谢谢。只是不得不问这是在帖子中保存主题标签的好设计模式吗?否则我应该做一个参考
    • 是的,为了向您保证,我建议您查看文档click me
    猜你喜欢
    • 1970-01-01
    • 2021-05-11
    • 2021-04-23
    • 2019-04-24
    • 2020-06-29
    • 2020-10-15
    • 2014-11-21
    • 2021-08-09
    • 2020-08-29
    相关资源
    最近更新 更多