简体   繁体   中英

TypeORM - Requirement nullable option in relationship for @OneToMany side

In a project I need a nullable ManyToOne - OneToMany relation between two different entities. For now I solved it like this:

L1Log Entity (ManyToOne side)

@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 Entity (OneToMany side)

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

My question is now whether or not the { nullable: true } option is needed in the @OneToMany side of the relation because the @OneToMany will be an empty array when there are no relations setup?

There is no need to set nullable: true on the One side of a OneToMany. If there are no L1Log items, then the query will return an empty array.

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

On the Many side of the relation you should set nullable: true . Also best practice is to make the type of the property DimonaCancel | null DimonaCancel | null . This is because it can return a null value and you can check this off if you use in your code.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM