Ask Your Question
2

How can composite Foreign Key be created on Postgres using Typeorm?

asked 2023-06-06 12:50:52 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-06-06 13:03:03 +0000

bukephalos gravatar image

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' })
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-06 12:50:52 +0000

Seen: 11 times

Last updated: Jun 06 '23