很多TypeOrm NestJs可以保存

问题描述 投票:0回答:1

我有一个问题,如何使用TypeORM多对多关系保存在NestJs中。我尝试推送只会响应,不会保存在cat和book的joinTable id中。谢谢!

service.ts

async addBookToCat(catId: string, bookId: string): Promise<any> {

    const cat =  await this.catRepository.findOne(catId);
    if(!cat) {
      throw new NotFoundException('Category not found!');
    }
    const book = await this.bookRepository.findOne(bookId);
    if(!book) {
      throw new NotFoundException('Book not found!');
    }
    cat.book.push(book);
    return cat; 
  }

Category.entity.ts

  @ManyToMany(type => Book, book => book.cat, {eager: true})
  @JoinTable()
  book: Book[];

Book.entity.ts

  @ManyToMany(type => Category, cat => cat.book, {eager: false, cascade: true})
  cat: Category[];
typescript many-to-many nestjs typeorm
1个回答
0
投票

您忘记了保存结果

...
cat.book.push(book);
return this.catRepository.save(cat);
© www.soinside.com 2019 - 2024. All rights reserved.