1、安装依赖
npm install --save @nestjs/typeorm typeorm mysql
2、在项目的根目录下创建一个ormconfig.json文件
{
"type": "mysql",
"host": "地址",
"port": 3306,
"username": "账号",
"password": "密码",
"database": "数据库",
"entities": ["dist/**/*.entity{.ts,.js}"],
"synchronize": false //不会在数据库自动生成表,我个人不太喜欢这种,所以自己写的原生sql
}
此处可能会有一个错误,typeorm版本和最新的nestjs略有不兼容,须参考bug fix部分做修改
参考此篇文章解决
3、在app.module.ts文件中使用数据库的配置
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CatModule } from './cat/cat.module';
// 引入数据库的及配置文件
import { TypeOrmModule, TypeOrmModuleOptions } from '@nestjs/typeorm';
@Module({
imports: [
CatModule,
TypeOrmModule.forRoot(), // 数据库的
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
4、创建一个entities文件夹,下面放实体类,例如form.entity.ts的实体类
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity("trainee")
export class FormEntity extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column({ type: "varchar", name: "name" })
name: string;
@Column({ type: "bigint", name: "phone" })
phone: number;
@Column({ type: "varchar", name: "email" })
email: string;
@Column({ type: "varchar", name: "university" })
university: string;
@Column({ type: "varchar", name: "major" })
major: string;
@Column({ type: "int", name: "position" })
position: number;
@Column({ type: "int", name: "city" })
city: number;
@Column({ type: "varchar", name: "vita" })
vita: string;
@Column({ type: "datetime", name: "createTime" })
createTime: string;
}
5、在form.module.ts中注册实体类Rents
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { FormEntity } from 'src/entities/form.entity';
import { FormController } from './form.controller';
import { FormService } from './form.service';
@Module({
imports: [TypeOrmModule.forFeature([FormEntity])],
controllers:[FormController],
providers: [FormService]
})
export class FormModule { }
6、在服务层@InjectRepository() 修饰器向 RentService 注入 RentRepository
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { FormEntity } from '../../entities/form.entity'
import { Repository } from 'typeorm';
import { FormReq } from 'src/interfaces/form.interface';
@Injectable()
export class FormService {
constructor(
@InjectRepository(FormEntity)
private readonly formRepository: Repository<FormEntity>
) { }
async submit(submitFormReq: FormReq) {
try {
return await this.formRepository.save(submitFormReq)
} catch {
throw new HttpException("服务器错误,请稍后再试", HttpStatus.FORBIDDEN)
}
}
}
TypeOrm的一些使用
- 1、save(添加数据到数据库)
return await this.formRepository.save(submitFormReq)
- 2、使用where条件查询数据
return await this.progressListEntity.find({ where: { status: 1 } })
- 3、使用原生sql语句
const res = await this.progressListEntity.query("select max(step) as max from recruitment_progress;")