背景
我使用 TypeORM 和 NestJS。
我有两个实体:
一次锻炼可以有多次锻炼,一次锻炼可以有多次锻炼。为了实现这一点,我使用了 ManyToMany 关系。
锻炼实体
@Entity()
export class Workout {
@PrimaryGeneratedColumn()
id: number;
@JoinTable()
@ManyToMany(() => Exercise, (exercise) => exercise.workouts)
exercises: Exercise[];
}
运动实体
@Entity()
export class Exercise {
@PrimaryGeneratedColumn()
id: number;
@ManyToMany(() => Workout, (workout) => workout.exercises)
workouts: Workout[];
}
一切正常,但当我尝试使用两个相同的练习创建锻炼时,我收到一条错误消息
duplicate key value violates unique constraint
。
问题:如何在多对多关系中拥有重复的实体?
在幕后它使用隐式多对多表:
|workout_id | excersise_id |
| 1 | 1 |
本例中的主键将使用这 2 个键进行组合。
为了解决您的问题,我建议将隐式多对多转换为显式:https://orkhan.gitbook.io/typeorm/docs/many-to-many-relations#many-to-many-relations-with -自定义属性
在您的情况下,您将有一个自定义属性
id
,这将解决duplicate key value violates unique constraint
,因为只有id
是唯一的。
希望有帮助。