我正在尝试与nestjs
,typeorm
和postgres
建立一对一的关系。
我有个人资料实体
@OneToOne(() => Trainer, trainer => trainer.profile)
@JoinColumn({ name: 'trainer_trainer_id' })
trainer!: Trainer;
和培训师实体
@OneToOne(() => Profile, profile => profile.trainer)
profile!: Profile;
当用户提交申请成为Trainer时,我想在trainer
表中用新行更新数据库,并在profile
表中添加关联的ID。
因此,在培训师存储库中,我这样做:
const trainer = CreateTrainerDto.toEntity(createTrainerDto);
trainer.profile = profile;
return await trainer.save();
这很好用,但是每次都会在trainer
表中创建一个新行(并相应地更新profile
表中的id)。但是我期望save()
如果已经保存了培训师,则将更新现有行。
我做错了吗?
答案 0 :(得分:1)
在实体上调用save函数时,可能会发生两种情况:
由于您的DTO名为createTrainerDto,因此我假设您未提供实体的ID。因此,此代码将始终在表中插入新行。
创建DTO,以便id属性是可选的,这样您就可以使用DTO进行创建和更新。例如:
export class TrainerDTO {
id?: number;
name: string;
profile: ProfileDTO;
}
答案 1 :(得分:1)
保存方法具有两种功能,即插入和更新。
如果提供的实体实例具有id值,则将执行更新,否则将插入。
因此,您可以执行以下操作:
const trainer = await this.trainerRepository.findOne(id) || this.trainerRepository.create(); // you can add the "or create" to have both create and update functionalities in one method
return await this.trainerRepository.save({...trainer, ...createTrainerDto, profile})