Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To create a composite foreign key on Postgres using Typeorm, you need to follow these steps:

  1. Define the table that will have the primary key:
@Entity()
export class Table1 {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  column1: string;

  @OneToMany(() => Table2, (table2) => table2.table1)
  table2s: Table2[];
}
  1. Define the table that will have the composite foreign key:
@Entity()
export class Table2 {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  column2: string;

  @ManyToOne(() => Table1, (table1) => table1.table2s)
  @JoinColumn({ name: 'table1_id' })
  table1: Table1;

  @ManyToOne(() => AnotherTable, (anotherTable) => anotherTable.table2s)
  @JoinColumn({ name: 'another_table_id' })
  anotherTable: AnotherTable;
}
  1. Use the @JoinColumn decorator to specify the name of the foreign key column.

You can customize the name of the foreign key column by passing a name option to the @JoinColumn decorator.

@JoinColumn({ name: 'table1_id' })

You can also specify multiple foreign keys by using multiple @JoinColumn decorators on the same column.

@JoinColumn({ name: 'table1_id' })
@JoinColumn({ name: 'another_table_id' })