我正在将Nest.js与TypeORM和Postgres一起使用。
我想做的是创建User
实体的实例。它具有Membership
和File
字段,它们也是实体。它们与User
具有一对一关系,因此在创建User
时创建。如果有任何问题,我想回滚所有内容,因此我正在使用事务。
这就是我在做什么:
async create(userProcessed: UserProcessed): Promise<UserResponse> {
const response: UserResponse = {
message: 'User not created',
success: false,
user: undefined,
};
const queryRunner = this.connection.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
const membership = new Membership();
membership.membershipState = userProcessed.membershipState;
membership.membershipType = userProcessed.membershipType;
const membershipSaved = await queryRunner.manager.save(membership);
if (!membershipSaved) throw Error();
const file = new File();
file.weight = userProcessed.file.weight;
file.height = userProcessed.file.height;
const fileSaved = await queryRunner.manager.save(file);
if (!fileSaved) throw Error(response.message);
const user = new User();
user.email = userProcessed.email;
user.firstName = userProcessed.firstName;
user.lastName = userProcessed.lastName;
user.gender = userProcessed.gender;
user.file = fileSaved;
user.membership = membershipSaved;
user.role = userProcessed.role;
user.birthday = new Date(userProcessed.birthday);
user.setPassword(userProcessed.password);
const userSaved = await this.userRepository.save(user);
console.log(userSaved);
if (!userSaved) throw Error(response.message);
response.success = true;
response.message = 'User created';
response.user = userSaved;
await queryRunner.commitTransaction();
return response;
} catch (e) {
await queryRunner.rollbackTransaction();
throw Error(response.message);
} finally {
await queryRunner.release();
}
}
创建用户时出现问题。在使用事务时,在我调用await queryRunner.commitTransaction();
之前(根据需要),什么也不会保存到数据库中。结果,我要用作外键的membership
和file
确实不存在。
有没有办法可以在同一笔交易中解决这个问题?
答案 0 :(得分:1)
这比我想象的要简单。
我刚刚发现可以在{ cascade: ['insert'] }
的{{1}}注释中设置@OneToOne
。这样一来,就不必在保存User
时保存File
之前保存Membership
或User
。
在User
中:
user.entity.ts
在 ...
@OneToOne(type => Membership, { cascade: ['insert'] })
@JoinColumn({ name: 'membership_id' })
membership: Membership;
@OneToOne(type => File, { cascade: ['insert'] })
@JoinColumn({ name: 'file_id' })
file: File;
...
user.service.ts
因此,所有内容都具有魅力!