如何在typeORM中的@ManyToMany中保存关系

How to save relation in @ManyToMany in typeORM

有 2 个名为 ArticleClassification 的实体。他们的关系是@ManyToMany.

我的问题是:如何保存关系?

我的代码如下:

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

我可以保存ArticleClassification成功。但是我不确定如何保存它们的关系。

我尝试通过以下代码保存关系:

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

还有这样的 post 数据结构

    {
        "name":"artile name",
        "content":"article content",
        "classification":[{
            "id":4
        },{
            "id":3
        }]
    }

一开始是可以的

但是当我再次post数据时,旧记录被替换而不是创建另一条记录。

接下来我该做什么?

请看下面的代码。

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

如何保存关系?

假设您有一组文章,并且您想要创建与分类实体的关系。您只需将数组分配给 属性 articles 并保存实体; typeorm 将自动创建关系。

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

要使其正常工作,必须先保存文章实体。如果想让typeorm自动保存文章实体,可以设置cascadetrue

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

在我的例子中,我有用户和角色,首先你必须在你的实体中初始化你的 manytomany :

在用户实体中:

@ManyToMany((type) => Role, {
    cascade: true,
  })
  @JoinTable({
    name: "users_roles",
    joinColumn: { name: "userId", referencedColumnName: "id" },
    inverseJoinColumn: { name: "roleId" }
  })
  roles: Role[];

在角色实体中:

  //Many-to-many relation with user
  @ManyToMany((type) => User, (user) => user.roles)
  users: User[];

在我的服务中,我从我的数据创建了一个新实体,然后我将角色数据添加到我的新实体对象:

let entity = await this.userRepository.create(data);
let entity2 = {
        ...entity,
        roles: data.selectedRoles,
      };
const user = await this.userRepository.save(entity2);

这是 typeorm 网站中的示例:

const category1 = new Category();
category1.name = "animals";
await connection.manager.save(category1);

const category2 = new Category();
category2.name = "zoo";
await connection.manager.save(category2);

const question = new Question();
question.title = "dogs";
question.text = "who let the dogs out?";
question.categories = [category1, category2];
await connection.manager.save(question);