【发布时间】:2021-08-07 09:37:43
【问题描述】:
为了学习,我做了一个项目来测试 TypeGraphql 和 TypeORM。我有一个User 和Book 实体,我想在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