Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save relation in @ManyToMany in typeORM

There are 2 entities named Article and Classification. 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 and Classification 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.

enter image description here

But when I post the data again, the old record was replaced rather create another record.

enter image description here

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;
  }
like image 250
Eve-Sama Avatar asked Feb 26 '19 12:02

Eve-Sama


People also ask

How do you save a relationship in TypeORM?

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.

How get data from many to many relationship in TypeORM?

Many-to-many is a relation where A contains multiple instances of B, and B contain multiple instances of A. Let's take for example Question and Category entities. A question can have multiple categories, and each category can have multiple questions. @JoinTable() is required for @ManyToMany relations.

How do you create a one to many relationship in TypeORM?

If you want to use @OneToMany , @ManyToOne is required. However, the inverse is not required: If you only care about the @ManyToOne relationship, you can define it without having @OneToMany on the related entity. Where you set @ManyToOne - its related entity will have "relation id" and foreign key.

What is relation in TypeORM?

Relations are used to refer the relationship between table in database. In general, a relationship exists between two tables when one of them has a foreign key that references the primary key of the other table. This feature makes relational database more powerful and efficiently store information.


1 Answers

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);
}
like image 151
Kim Kern Avatar answered Oct 22 '22 09:10

Kim Kern