1. 批量更新数据以及关联数据
user.controller.ts
@Patch('/update')
updateUser(@Body() dto: any) {
const user = dto as User;
return this.userService.update(user);
}
user.service.ts
async update(body) {
if (!body.id) {
return 'id不能为空';
}
// 更新多个模型数据
const userTemp: any = await this.findProfile(body.id);
const newUser = this.user.merge(userTemp, body); // 合并数据
return this.user.save(newUser);
// return this.user.update(query.id, query); // 更新单个模型
}
findProfile(id: number) {
return this.user.findOne({
where: {
id,
},
relations: { profile: true },
});
}
注意: @OneToOne(() => Profile, (profile) => profile.user, { cascade: true }) // cascade:设置cascade为true 子数据也自动插入数据库