database design - Whether can be defined foreign key using or in typeORM? - Stack Overflow

admin2025-05-02  1

When design the tables I get doubt (below is the pseudo-code) :

Node Table {
  id: number,
  label: string
}

Comb Table {
  id: number,
  label: string
}


Link Table {
  source: // Here it can be an instance of the Node table or an instance of the Comb table
  target: // Here it can be an instance of the Node table or an instance of the Comb table
}

Excuse me, when we define the Link table, do we have to define it with only 4 fields?

Link Table {
  nodesource: Node,
  nodetarget: Node,
  combsource: Comb,
  combtarget: Comb, 
}

the actual code:


export enum EdgeType {
  NodeToNode = 'NodeToNode',
  NodeToComb = 'NodeToComb',
  CombToComb = 'CombToComb',
  CombToNode = 'CombToNode'
}

@Entity()
export class Link {
  @PrimaryGeneratedColumn()
  id: number | undefined

  // type
  @Column({
    type: 'enum',
    enum: LinkType,
    nullable: false,
    default: LinkType.NodeToNode
  })
  type!: LinkType

  // Node:source
  @OneToOne(type => Node)
  @JoinColumn()
  nodeSource?: Node

  // Node:target
  @OneToOne(type => Node)
  @JoinColumn()
  nodeTarget?: Node

  // Combo:source
  @OneToOne(type => Comb)
  @JoinColumn()
  combSource?: Comb

  // Combo:target
  @OneToOne(type => Comb)
  @JoinColumn()
  combTarget?: Comb

whether cannot be defined like this:


@Entity()
export class Link {
  @PrimaryGeneratedColumn()
  id: number | undefined

  @OneToOne(type => Node|Comb)
  source: Node | Comb
  @OneToOne(type => Node|Comb)
  target: Node | Comb

The idea here was to use a more generic approach where the source and target fields could directly accept either a Node or a Comb instance.

But I don't know this approach whether supported by the database or the typeORM framework.

转载请注明原文地址:http://www.anycun.com/QandA/1746134193a92048.html