TypeORM 如何在@ManyToMany 中更新与多个 ID 的关系?

TypeORM How to UPDATE relations with multiple IDs in @ManyToMany?

我已经尝试过这个 , read this issue 并且我发现的解决方案在尝试插入新记录时似乎工作正常。但是,我无法使用相同的方法更新现有记录的关系,当我尝试这样做时出现错误 [ExceptionsHandler] Cannot query across many-to-many for 属性 流派.

这是我的代码片段

@Entity({ name: 'movies' })
export default class Movie extends Content {
  @PrimaryGeneratedColumn()
  id: number;

  @ManyToMany(() => Genre, (genre) => genre.movies, { cascade: true })
  @JoinTable()
  genres: Genre[];
}


@Entity({ name: 'genres' })
export default class Genre {
  @PrimaryGeneratedColumn()
  id: number;

  @ManyToMany(() => Movies, (movies) => movies.genres)
  movies: Movies[];
}
// This method is working just fine!
async insert({ genres, ...others }: CreateMovieDto): Promise<Movie> {
  const record = this.moviesRepo.create(others);
  record.genres = genres.map((id) => ({ id } as Genre)); // this results an array like [{ id: 3 }]
  return await this.moviesRepo.save(record);
}

// This method is NOT working
// ERROR: [ExceptionsHandler] Cannot query across many-to-many for property genres
async update(id: number, { genres, ...others }: CreateMovieDto): Promise<Movie> {
  const record = this.moviesRepo.create(others);
  record.genres = genres.map((id) => ({ id } as Genre)); // this results an array like [{ id: 3 }]
  return await this.moviesRepo.update(id, record);
}

我最终使用 Repository.save() 而不是 Repository.update()。根据 Repository API 文档,您也可以使用 .save() 来更新记录。

If the entity already exist in the database, it is updated. If the entity does not exist in the database, it is inserted.

async update(id: number, { genres, ...others }: CreateMovieDto): Promise<Movie> {
  const record = this.moviesRepo.create(others);
  record.genres = genres.map((id) => ({ id } as Genre));
  // don't forget add the id and make sure it's type of number
  record.id = id;
  // .update was changed to .save()
  return await this.moviesRepo.save(record);
}

P.S。在更新记录之前,请先确保它存在。否则,将创建一个新记录。