【问题标题】:Usage of ManyToOne relation returns null in TypeGraphQL在 TypeGraphQL 中使用 ManyToOne 关系返回 null
【发布时间】:2021-08-07 09:37:43
【问题描述】:

为了学习,我做了一个项目来测试 TypeGraphql 和 TypeORM。我有一个UserBook 实体,我想在Book 实体上有一个created_by 字段。

@ObjectType()
@Entity()
export class Book extends BaseEntity {
  @Field(() => ID)
  @PrimaryGeneratedColumn()
  readonly id: number;

  @Field({ nullable: true })
  @Column({ nullable: true })
  name: string;

  @Field(() => User)
  @ManyToOne(() => User)
  @JoinColumn({ name: 'created_by' })
  created_by: User;
  // @RelationId((orthodontist: Orthodontist) => orthodontist.created_by)
  // createdById: number;
}

@ObjectType()
@Entity()
export class User extends BaseEntity {
    @Field(() => ID)
    @PrimaryGeneratedColumn()
    id: number;

    @Field({ nullable: true })
    @Column({ nullable: true })
    first_name?: string;

    @Field({ nullable: true })
    @Column({ nullable: true })
    last_name?: string;

    @Field()
    @Column({ unique: true })
    email: string;

    @Column()
    password: string;

    @Field(() => [Book!])
    @OneToMany(() => Book, book => book.created_by)
    created_books: Book[];

}

对于我的解析器,它看起来像这样,正如文档所说,我正在正确加载。

@Resolver(Book)
export class OrthodontistResolver {

    @Query(() => [Book])
    books(): Promise<Book[]> {
        return Book.find();
    }
}

当我进入我的 GraphQL 游乐场并查询如下内容时:

{
  books {
    name,
    id,
  }
}

一切正常并返回正确的数据。但是,当我尝试像这样使用 created_by 字段时:

{
  orthodontists {
    name,
    id,
    created_by {
      id
    }
  }
}

它给了我以下错误:

不能为不可为空的字段 Book.created_by 返回 null。

我确保该关系存在于数据库中,并使用它的 FK 正确设置。但这又是从哪里来的呢?我怎样才能解决这个问题?我确实尝试过使用@RelationId 装饰器,如第一个代码示例所示。不幸的是,它没有工作。

编辑:

数据库中只有一本书,其中created_by字段不为空。

【问题讨论】:

    标签: node.js typescript typeorm typegraphql


    【解决方案1】:

    在使用find 操作时,更改您的books 解析器以返回关系created_by

    @Resolver(Book)
    export class OrthodontistResolver {
    
      @Query(() => [Book])
      books(): Promise<Book[]> {
        return Book.find({
          relations: ["created_by"],
        });
      }
    }
    

    【讨论】:

    • 每个要使用的关系都需要这个吗?
    • 这取决于您定义关系的方式。例如,如果您有@ManyToOne(() =&gt; User, { eager: true }),则无需在find 中添加relations。否则,您必须在使用find 时明确告知您需要加载哪些关系。您可以查看eager and lazy loading in typeorm 了解更多信息。
    • 确实如此。谢谢!
    猜你喜欢
    • 2016-10-24
    • 1970-01-01
    • 2021-04-21
    • 2020-12-24
    • 2014-08-21
    • 2019-05-17
    • 2019-07-11
    相关资源
    最近更新 更多