我正在使用 NestJS 10 和 TypeORM 0.3.17。我已经用 @OneToOne 关系定义了这个实体
@Entity()
export class User {
@PrimaryGeneratedColumn('uuid')
id: string;
...
@Column()
password: string;
@OneToOne(() => Contact, {
cascade: true,
onDelete: 'CASCADE',
nullable: true,
})
@JoinColumn({ name: 'contact_id', referencedColumnName: 'id' })
contact?: Contact;
}
我已经定义了对应的UpdateUserDto和CreateUserDto...
export class UpdateUserDto extends PartialType(CreateUserDto) {
}
export class CreateUserDto {
email: string;
password: string;
refreshToken: string;
contact: CreateContactDto;
}
如何创建服务方法来更新联系人对象中的单个字段?我试过这个
export class UsersService {
constructor(
private readonly userRepository: UserRepository, // import as usual
) {}
...
async update(
id: string,
updateUserDto: UpdateUserDto,
): Promise<UpdateResult> {
return this.userRepository.update(id, updateUserDto);
}
但是当我用参数调用这个方法时
this.usersService.update(userId, {
contact: {
firstName: 'Dave',
lastName: 'Test',
mailingAddress: {
addressLine1: '321 oklahoma',
city: 'Springfield',
zipCode: '90210',
region: { id: '123' }
}
}
});
由于运行时错误而失败
[ExceptionsHandler] Property "contact.firstName" was not found in "User". Make sure your query is correct.
首先通过ID找到用户:
this. userRepository.findOneBy({id});
if (!user) throw new NotFoundException();
然后创建联系人对象;
const contact = new Contact();
contact.frstName = "Dave";
...
最后,您可以保存关系:
user.contact = contact;
userRepository.save(user);
就我而言,我会这样做:
const user = await User.findOneOrFail({
where: { id || IsNull() }, //in case of id null and not getting the first row in db
relations: ['contact'],
});
Object.assign(user.contact, {
firstName: 'Dave',
lastName: 'test',
//...your rest
}); //if the user doesn't have a contact, it will create a new one
await user.save();