我正在尝试使用TypeORM中的自定义ManyToMany字段保存实体
主要实体
@Entity()
export class Routine extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column('varchar', { length: 50 })
name: string;
@Column('timestamptz')
creationDate: Date;
@Column('boolean')
active: boolean;
@ManyToOne(
type => User,
user => user.routines,
{ eager: false },
)
user: User;
@Column()
userId: number;
@OneToMany(
type => ExerciseToRoutine,
exerciseToRoutine => exerciseToRoutine.routineId,
)
public exerciseToRoutine: ExerciseToRoutine[];
}
JoinTable
@Entity()
export class ExerciseToRoutine extends BaseEntity {
@PrimaryColumn()
exerciseId: number;
@PrimaryColumn()
routineId: number;
@Column()
day: number;
@ManyToOne(
type => Routine,
routine => routine.exerciseToRoutine,
)
routine: Routine;
@ManyToOne(
type => Exercise,
exercise => exercise.exerciseToRoutine,
)
exercise: Exercise;
}
试图保存实体的代码
const routine = new Routine(name, currentDate, user, exerciseToRoutine, false);
await this.trySaveRoutine(routine);
问题在于,在自动生成常规ID之前,我需要将Routine实体及其executionToRoutine(JoinTable转换为Exercise Entity)保存起来,而属性ExerciseToRoutine需要该ID。那么我应该怎么做呢?谢谢
答案 0 :(得分:0)
OneToMany
的{{1}}字段exerciseToRoutine
不会存储到Routine
的任何外键,这将自行执行联接表。要保存新的ExerciseToRoutine
实体,只需将Routine
字段设置为空数组即可。然后使用新生成的exerciseToRoutine
id创建一个ExerciseToRoutine
。