Search code examples
node.jstypeormnode.js-typeorm

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?


Solution

  • 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. 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