rickster
rickster

Reputation: 324

How to save many-to-many relation in typeorm?

I am trying to make a relation between Posts and Hashtags, here are my both entities,

@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;
}

By these, typeorm created a database posts_hashtags_relation, with columns postsId and hashtagsId And the service by which I am saving hashtags in the hashtags table is like this

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;
  }

But how to save the relation in posts_hashtags_relation table ?

Upvotes: 0

Views: 450

Answers (1)

Ayoub Touba
Ayoub Touba

Reputation: 3007

As you notice in your post entity you have the column hashtags: Hashtags[]; the same thing in Hashtags...

So you can save the data of the relation in both entities:
with your code we can do:

...
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);

Upvotes: 1

Related Questions