How to save relation in @ManyToMany in typeORM

后端 未结 1 1521
耶瑟儿~
耶瑟儿~ 2020-12-20 16:56

There are 2 entities named Article and Classification. And the relation of them is @ManyToMany.

Here\'s my question: How to sa

相关标签:
1条回答
  • 2020-12-20 17:21

    How to save relations?

    Let's assume you have an array of articles and you want to create a relation to a classification entity. You just assign the array to the property articles and save the entity; typeorm will automatically create the relation.

    classification.articles = [article1, article2];
    await this.classificationRepository.save(classification);
    

    For this to work, the article entities have to be saved already. If you want typeorm to automatically save the article entities, you can set cascade to true.

    @ManyToMany(type => Article, article => article.classifications, { cascade: true })
    

    Your example

    async create(dto: ArticleClassificationDto): Promise<any> {
      let article = await this.repository.create(dto);
      article = await this.repository.save(article);
      const classifications = await this.classificationRepository.findByIds(article.classification, {relations: ['articles']});
      for (const classification of classifications) {
        classification.articles.push(article);
      }
      return this.classificationRepository.save(classifications);
    }
    
    0 讨论(0)
提交回复
热议问题