首页 > 解决方案 > 使 Mikro-ORM 关系字段可选

问题描述

我正在使用 mikro-orm 生成 graphql 模式,并且我的一对一关系中的所有字段都需要返回。如何让它们成为可选的,以便当字段返回 null 时我的查询不会引发错误?这是我在ticket.entity.ts 中定义关系的方式

@Field(() => Order, { nullable: true })
  @OneToOne(() => Order, null, { nullable: true })
  public order?: Order;

在我生成的tickets.schema.graphql 中,Order 对象返回:

type Order {
  id: ID!
  createdAt: DateTime!
  updatedAt: DateTime!
  archivedAt: DateTime
  client: String!
  soldDate: DateTime!
  type: String!
  ...
  ...
  ...
}

在我的 Order 实体中,所有字段都是可选的,生成的 SQL 表也可以这样理解它们。

export class Order extends BaseEntity {
  @Field(() => String)
  @Property({ nullable: true })
  public client: string;

  @Field(() => Date)
  @Property({ columnType: "date", nullable: true })
  public soldDate: Date;

  @Field(() => String)
  @Property({ nullable: true })
  public type: string;

  ...
  ...
  ...

我与我的订单实体中的工单没有一对一的关系。门票有订单,但订单不一定有门票。我在文档中没有看到单向关系,所以我想我会把它放在这里,以防它与我的问题有关。

标签: graphqlnestjsapollomikro-orm

解决方案


我的字段需要在订单实体中为空。这是与@nestjs/graphql 相关的问题,而不是与 mikro-orm 相关的问题。

export class Order extends BaseEntity {
  @Field(() => String, { nullable: true} )
  @Property({ nullable: true })
  public client: string;

  @Field(() => Date, { nullable: true} )
  @Property({ columnType: "date", nullable: true })
  public soldDate: Date;

  @Field(() => String, { nullable: true} )
  @Property({ nullable: true })
  public type: string;

推荐阅读