首页 > 解决方案 > 如何查询和改变表中的“多对多”字段?

问题描述

我是nestjs的新手。我有两个实体:

@Entity({ name: "Books" })
@ObjectType()
export class Book {
  @PrimaryGeneratedColumn()
  @Field()
  id: number;
  @Column()
  @Field()
  title: string;
  @ManyToMany(() => Author, (author: Author) => author.books)
  @Field(() => [Author])
  authors: Author[];
}
@Entity({ name: "Authors" })
@ObjectType()
export class Author {
  @PrimaryGeneratedColumn()
  @Field()
  id: Number;
  @Column()
  @Field()
  firstName: string;
  @Column()
  @Field()
  lastName: string;
  @ManyToMany(() => Book, (book: Book) => book.authors)
  @JoinTable()
  @Field(() => [Book])
  books: Book[];
}

这会自动给我第三个空表“authors_books_books”。如何建立作者与书籍的关系?不仅在摘要作者和摘要书之间,而且还指定这个具有 id:x 的作者写了具有 id:y? 的书。换句话说:如何用数据填充“authors_books_books”表?

标签: typescriptgraphqlnestjsapollotypeorm

解决方案


Typeorm 在技术上确实有内置的方法来处理这个......

也就是说,我更喜欢不需要对象的快速方法:

await this.manager.query(
    'INSERT INTO authors_books_books ("authorId", "bookId") VALUES ($1, $2)',
    [authorId, bookId],
);

推荐阅读