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

TypeORM@JoinTable()如何指定自定义联接列?

4 个月前提问
3 个月前修改
浏览次数27

1个答案

1

在TypeORM中,使用@JoinTable装饰器可以创建多对多关系的联接表。如果想要指定自定义联接列名称,你可以在@JoinTable装饰器中使用joinColumninverseJoinColumn选项来定制。

以下是一个例子,演示了如何在@JoinTable中指定自定义联接列:

typescript
import { Entity, PrimaryGeneratedColumn, Column, ManyToMany, JoinTable } from 'typeorm'; import { AnotherEntity } from './AnotherEntity'; @Entity() export class YourEntity { @PrimaryGeneratedColumn() id: number; // 与AnotherEntity的多对多关系 @ManyToMany(type => AnotherEntity) @JoinTable({ name: 'custom_join_table', // 联接表的自定义名称 joinColumn: { name: 'your_entity_id', // 自定义当前实体在联接表中的列名 referencedColumnName: 'id' // 指向YourEntity的主键 }, inverseJoinColumn: { name: 'another_entity_id', // 自定义另一个实体在联接表中的列名 referencedColumnName: 'id' // 指向AnotherEntity的主键 } }) anotherEntities: AnotherEntity[]; }

在这个例子中,YourEntityAnotherEntity实现了多对多关系。通过@JoinTable装饰器,我们自定义了联接表的名称为custom_join_table,同时指定了联接列的名称分别为your_entity_idanother_entity_id,对应地分别链接到YourEntityAnotherEntity的主键列。

referencedColumnName属性通常用于指定该外键列指向关联表中的哪一列,通常是主键列,但是也可以是任何唯一列。

此外,如果需要在联接表中定义额外的列或复杂的键,你可能需要手动创建联接表实体并使用一对多 / 多对一关系来替代多对多关系。

2024年6月29日 12:07 回复

你的答案