1 | initial version |
To create a composite foreign key on Postgres using Typeorm, you need to follow these steps:
@Entity()
export class Table1 {
@PrimaryGeneratedColumn()
id: number;
@Column()
column1: string;
@OneToMany(() => Table2, (table2) => table2.table1)
table2s: Table2[];
}
@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;
}
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' })