【问题标题】:How to query and mutate "many-to-many" fields in my table?如何查询和改变表中的“多对多”字段?
【发布时间】:2021-11-24 06:17:06
【问题描述】:

我是 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”表?

【问题讨论】:

    标签: typescript graphql nestjs apollo typeorm


    【解决方案1】:

    Typeorm 在技术上确实有 built-in ways to handle this...

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-22
      • 2012-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 1970-01-01
      相关资源
      最近更新 更多