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 子数据也自动插入数据库
pnpm i --save class-validator class-transformer
2.1 main.ts引入
import { ValidationPipe } from '@nestjs/common';
app.useGlobalPipes(new ValidationPipe());
2.2 使用
创建dto.ts
import { IsNotEmpty, IsString, Length } from 'class-validator';
export class SignUserDto {
@IsString()
@IsNotEmpty()
@Length(6, 20)
username: string;
@IsString()
@IsNotEmpty()
@Length(6, 20)
password: string;
}
使用:auth.controller.ts
import {
Body,
Controller,
Post,
UseFilters,
} from '@nestjs/common';
import { AuthService } from './auth.service';
import { TypeormFilter } from 'src/filters/typeorm.filter';
import { SignUserDto } from './dto/sign-user.dto';
@Controller('auth')
@UseFilters(new TypeormFilter())
export class AuthController {
constructor(private authService: AuthService) {}
@Post('signin')
signin(@Body() body: SignUserDto) {
const { username } = body;
return this.authService.signin(username);
}
}