如何在typeORM中保存@ManyToMany中的关系 [英] How to save relation in @ManyToMany in typeORM
问题描述
有 2 个实体名为 Article
和 Classification
.它们的关系是@ManyToMany
.
这是我的问题:如何保存关系?
我的代码如下:
@Entity()出口类文章{@PrimaryGeneratedColumn()身份证号码;@柱子()名称:字符串;@CreateDateColumn()创建时间:日期;@UpdateDateColumn()更新时间:日期;@柱子({类型:'文本',})内容:字符串;@柱子({默认值:0,})喜欢数量:数量;@柱子({默认值:0,})评论数量:数量;}@实体()出口类分类{@PrimaryGeneratedColumn()身份证号码;@CreateDateColumn()创建时间:日期;@UpdateDateColumn()更新时间:日期;@柱子()名称:字符串;@ManyToMany(类型=>文章)@JoinTable()文章:文章[];}
我可以成功保存文章
和分类
.但我不确定如何保存它们的关系.
我尝试通过以下代码保存关系:
async create(dto: ArticleClassificationDto): Promise
到但是当我再次发布数据时,旧记录被替换而不是创建另一个记录.
接下来我该怎么办?
请看下面的代码.
async create(dto: ArticleClassificationDto): Promise
{this.repository.save(dto).then(article => {article.classification.forEach(item => {this.ClassificationRepository.findOne({//privous 方法是从数据库中获取所有文章并推送到这个数组中//关系:['文章'],其中:{ id: item }//现在我改变了数据结构,只包含 id 而不是 {id}}).那么(分类=> {//console.log(文章);控制台日志(分类);//cmd 将显示 ' UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'push' of undefined' withoutous 下面行代码.但是如果我手动初始化数组,旧记录将被再次替换.//分类.文章 = [];分类.文章.推(文章);this.ClassificationRepository.save(分类);});})})返回空;} 解决方案如何保存关系?
假设您有一组文章,并且您想要创建与分类实体的关系.您只需将数组分配给属性
articles
并保存实体;typeorm 将自动创建关系.classification.articles = [article1, article2];等待 this.classificationRepository.save(classification);
为此,必须已保存文章实体.如果想让typeorm自动保存文章实体,可以设置<代码>级联
true
.@ManyToMany(type => Article, article => article.classifications, { cascade: true })
<小时>
你的例子
async create(dto: ArticleClassificationDto): Promise
{让文章 = 等待 this.repository.create(dto);article = await this.repository.save(article);const 分类 = 等待 this.classificationRepository.findByIds(article.classification, {relations: ['articles']});for (const 分类的分类) {分类.文章.推(文章);}返回 this.classificationRepository.save(classifications);} There are 2 entities named
Article
andClassification
. And the relation of them is@ManyToMany
.Here's my question: How to save the relation?
My code as below:
@Entity() export class Article { @PrimaryGeneratedColumn() id: number; @Column() name: string; @CreateDateColumn() createTime: Date; @UpdateDateColumn() updateTime: Date; @Column({ type: 'text', }) content: string; @Column({ default: 0, }) likeAmount: number; @Column({ default: 0, }) commentAmount: number; } @Entity() export class Classification { @PrimaryGeneratedColumn() id: number; @CreateDateColumn() createTime: Date; @UpdateDateColumn() updateTime: Date; @Column() name: string; @ManyToMany(type => Article) @JoinTable() articles: Article[]; }
I can save the
Article
andClassification
successful. But I'm not sure how to save the relation of them.I have tried to save the relation via below code:
async create(dto: ArticleClassificationDto): Promise<any> { const article = this.repository.save(dto); article.then(value => { console.log(value);//console the object article value.classification.forEach(item => { const classification = new Classification(); classification.id = item.id; classification.articles = []; classification.articles.push(value); this.classificationService.save(classification); }) }); console.log(article); return null; }
And the post data strcture like that
{ "name":"artile name", "content":"article content", "classification":[{ "id":4 },{ "id":3 }] }
At the beginning, it works.
But when I post the data again, the old record was replaced rather create another record.
What should I do next?
Just look below code please.
async create(dto: ArticleClassificationDto): Promise<any> { this.repository.save(dto).then(article => { article.classification.forEach(item => { this.ClassificationRepository.findOne( { // the privous method is get all the articles from databse and push into this array // relations: ['articles'], where: { id: item }// now I change the data strcture, just contains id instead of {id} } ).then(classification => { // console.log(article); console.log(classification); // cmd will show ' UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'push' of undefined' withous below line code. But if I init the array manually,the old record will be replaced again. // classification.articles = []; classification.articles.push(article); this.ClassificationRepository.save(classification); }); }) }) return null; }
解决方案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
totrue
.@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); }
这篇关于如何在typeORM中保存@ManyToMany中的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!