There are 2 entities named Article
and Classification
. And the relation of them is @ManyToMany
.
Here\'s my question: How to sa
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 })
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);
}