安装依赖
yarn add @nestjs/typeorm typeorm mysql
配置mysql
// mysql
import { TypeOrmModule } from "@nestjs/typeorm";
// 模块
import { MysqldemoModule } from "./mysqldemo/mysqldemo.module";
@Module({
// 连接mongodb数据库
imports: [
MysqldemoModule, // 模块
TypeOrmModule.forRoot({
type:"mysql",
host:"localhost",
port:3306,
username:"root",
password:'12345678',
database:"test",
entities:[__dirname+'/**/*.entity{.ts,.js}'], // 实体
synchronize:true // 同步?
})
],
})
定义实体
import { Entity ,PrimaryGeneratedColumn , Column} from 'typeorm';
@Entity()
export class Mysql{
// 自增主键
@PrimaryGeneratedColumn()
id:number;
// Column : 如果数据库没有自动创建
@Column({length:255})
name:string;
@Column('int')
age:number
}
配置模块
import { Module } from '@nestjs/common';
// 配置模块
import { TypeOrmModule } from '@nestjs/typeorm'
// 实例
import { Mysql } from "../entity/mysql.entity";
import { MysqldemoController } from "./mysqldemo.controller";
import { MysqldemoService } from './mysqldemo.service';
@Module({
controllers:[MysqldemoController],
imports:[
TypeOrmModule.forFeature([Mysql])
],
providers: [MysqldemoService]
})
export class MysqldemoModule {}
接口
import { Controller, Get } from '@nestjs/common';
import { MysqldemoService } from "./mysqldemo.service";
@Controller('mysqldemo')
export class MysqldemoController {
constructor(
private readonly mysqldemoService:MysqldemoService
){}
@Get()
index(){
return this.mysqldemoService.findAll()
}
}
服务
import { Injectable } from '@nestjs/common';
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { Mysql } from '../entity/mysql.entity';
@Injectable()
export class MysqldemoService {
constructor(
// 把实例 赋值给变量
@InjectRepository(Mysql)
private readonly mysqlRepository:Repository<Mysql>
){}
findAll(){
return this.mysqlRepository.find()
}
}