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

Viewed 2162

I already tried this answer, read this issue and the solution I found seems to be working fine when trying to insert a new record. however, I cannot update the relations of already existing records using the same approach, when I try to do so I'm getting the error [ExceptionsHandler] Cannot query across many-to-many for property genres.

Here's a snippet of my code

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

I ended up using Repository.save() instead of Repository.update(). according to the Repository API documentation, you can use .save() to update records as well.

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. Before updating the record please make sure it exists first. otherwise, a new record will be created.

Related