乐闻世界logo
搜索文章和话题

TypeORM @ JoinTable how to specify custom join columns?

1个答案

1

In TypeORM, the @JoinTable decorator is used to define a join table for many-to-many relationships. If you wish to specify custom join column names, you can customize them by using the joinColumn and inverseJoinColumn options within the @JoinTable decorator.

Here is an example demonstrating how to specify custom join columns within @JoinTable:

typescript
import { Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable } from 'typeorm'; import { AnotherEntity } from './AnotherEntity'; @Entity() export class YourEntity { @PrimaryGeneratedColumn() id: number; // Many-to-many relationship with AnotherEntity @ManyToMany(type => AnotherEntity) @JoinTable({ name: 'custom_join_table', // Custom join table name joinColumn: { name: 'your_entity_id', // Custom column name for the current entity in the join table referencedColumnName: 'id' // References the primary key of YourEntity }, inverseJoinColumn: { name: 'another_entity_id', // Custom column name for the other entity in the join table referencedColumnName: 'id' // References the primary key of AnotherEntity } }) anotherEntities: AnotherEntity[]; }

In this example, YourEntity and AnotherEntity implement a many-to-many relationship. By using the @JoinTable decorator, we customize the join table name to custom_join_table and specify the join column names as your_entity_id and another_entity_id, respectively, linking to the primary key columns of YourEntity and AnotherEntity.

The referencedColumnName property is typically used to specify which column in the related table the foreign key column references; it is usually the primary key column but can reference any unique column.

Additionally, if you need to define additional columns or complex keys in the join table, you may need to manually create a join table entity and use a one-to-many or many-to-one relationship to replace the many-to-many relationship.

2024年6月29日 12:07 回复

你的答案