【问题标题】:TypeORM - Requirement nullable option in relationship for @OneToMany sideTypeORM - @OneToMany 方关系中的要求可为空的选项
【发布时间】:2022-09-23 17:14:35
【问题描述】:

在一个项目中,我需要两个不同实体之间的可为空的 ManyToOne - OneToMany 关系。现在我这样解决了:

L1Log 实体(ManyToOne 端)

@Entity()
export class L1Log extends BaseEntity {
  @PrimaryGeneratedColumn(\'uuid\')
  uuid: string

  @Column({ type: \'varchar\', nullable: true })
  dimonaCancelUuid?: string

  @ManyToOne(() => DimonaCancel, dimonaCancel => dimonaCancel.l1Logs, { nullable: true })
  @JoinColumn({ name: \'dimonaCancelUuid\' })
  dimonaCancel?: DimonaCancel
}

DimonaCancel 实体(OneToMany 方)

@Entity()
export class DimonaCancel extends BaseEntity {
  @PrimaryGeneratedColumn(\'uuid\')
  uuid: string
  
  @OneToMany(() => L1Log, l1Log => l1Log.dimonaCancel, { nullable: true })
  l1Logs?: L1Log[]
}

我现在的问题是{可为空:真}选项中需要@OneToMany关系的一边,因为@OneToMany没有关系设置时会是一个空数组吗?

    标签: node.js typeorm node.js-typeorm


    【解决方案1】:

    无需在 OneToMany 的一侧设置nullable: true。如果没有L1Log 项,则查询将返回一个空数组。

      @OneToMany(() => L1Log, l1Log => l1Log.dimonaCancel)
      l1Logs?: L1Log[]
    

    在关系的多方面,您应该设置nullable: true。最佳实践也是使属性的类型为DimonaCancel | null。这是因为它可以返回一个空值,如果您在代码中使用,您可以将其选中。

      @ManyToOne(() => DimonaCancel, dimonaCancel => dimonaCancel.l1Logs, { nullable: true })
      @JoinColumn({ name: 'dimonaCancelUuid' })
      dimonaCancel?: DimonaCancel | null
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 2021-04-04
      • 1970-01-01
      • 1970-01-01
      • 2014-09-10
      • 2021-05-17
      • 1970-01-01
      相关资源
      最近更新 更多