【问题标题】:Graphql field is always nullGraphql 字段始终为空
【发布时间】:2021-07-18 22:49:12
【问题描述】:

嘿,我尝试访问架构中的外键值。

@ObjectType()
@Entity("Vehicle")
export class Vehicle extends BaseEntity {
  @Field(() => Int)
  @PrimaryColumn()
  id!: number;

  @Field(() => String)
  @Column({unique: true})
  serial_id!: String;

  @ManyToOne(() => Vehicle_Model, model => model.id)
  @JoinColumn({ name: 'model' })
  model!: Vehicle_Model;

  @OneToOne(() => Battery)
  @JoinColumn({ name: 'battery' })
  battery!: number;

  @ManyToOne(() => Operator, operator => operator.id)
  @JoinColumn({ name: 'operator' })
  @Field()
  operator: Operator;

  @Field(() => String)
  @CreateDateColumn()
  created: Date;
}

例如,我想访问我的 graphql-playground 中的 operator 字段,而 operator 中的 id 是我的 Operator 类的主键。

@ObjectType()
@Entity()
export class Operator extends BaseEntity {
  @Field()
  @PrimaryGeneratedColumn()
  id!: number;

  @Field(() => String)
  @Column({ unique: true })
  email!: string;

  @Column()
  password!: string;

  @Field(() => String)
  @CreateDateColumn()
  created: Date;
}

这是 Operator 类。 现在,当我尝试访问 operator 字段时,我收到以下错误: “不能为不可为空的字段 Vehicle.operator 返回 null。”

我可以获得所有正常值,例如 serial_id 或 created 但不是我的外键。

我希望任何人都可以帮助我:)

谢谢

【问题讨论】:

    标签: database postgresql graphql typeorm typegraphql


    【解决方案1】:

    你定义@ManyToOne关系的方式应该改变如下:

    @ObjectType()
    @Entity("Vehicle")
    export class Vehicle extends BaseEntity {
      @ManyToOne(() => Operator)
      // '@JoinColumn' specifies which column in your 'Vehicle' entity contains the
      // foreign key to 'Operator' entity. It should not be equal to the name of the
      // relation. You can simply remove '@JoinColumn' or use a different name and
      // define that column in your entity like below
      @JoinColumn({ name: 'operatorId' })
      @Field()
      operator: Operator;
    
      @Column()
      operatorId: number;
    }
    

    你应该检查你所有的关系,因为我发现它们也没有相应地定义。

    我建议您在继续之前阅读Many-to-one / one-to-many relationsOne-to-one relations 文档。

    此外,如果您在查询时没有将Vehicle 实体与Operator 实体连接起来,您还应该查看Eager and Lazy Relations 文档。

    希望这会有所帮助。干杯? !!!

    【讨论】:

      猜你喜欢
      • 2015-07-24
      • 2020-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      相关资源
      最近更新 更多