下插件
λ yarn add @nestjs/typeorm typeorm mysql
创建 cats模块, 控制器,service
λ nest g mo cats
λ nest g co cats
λ nest g s cats cats/
链接mysql 链接出现下面的错误
Client does not support authentication protocol requested by server; consider u pgrading MySQL client 如果出现这个错误 ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '你的数据库密码';
// app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { TypeOrmModule } from '@nestjs/typeorm'; #
import { Connection } from 'typeorm'; #
import { CatsModule } from './cats/cats.module';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'mysql登录密码',
database: 'nest',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
}), #
CatsModule
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {
constructor(private readonly connection: Connection) {} #
}
编辑 entity
// cats.entity.ts
import { PrimaryGeneratedColumn, Column, Entity } from "typeorm";
@Entity()
export class Cats {
@PrimaryGeneratedColumn()
id: number;
@Column({length: 45})
name: string;
@Column('int')
age: number;
}
在cats.module.ts 中使用
import { TypeOrmModule } from '@nestjs/typeorm';
import { Cats } from './cats.entity';
@Module({
imports: [TypeOrmModule.forFeature([Cats])],
})
export class CatsModule {}
注入 cats.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Cats } from './cats.entity';
import { Repository } from 'typeorm';
@Injectable()
export class CatsService {
constructor(
@InjectRepository(Cats)
private readonly catsRepository: Repository<Cats>
) { }
find(){
return this.catsRepository.find()
}
getCat(name:string): Promise<Cats[]> {
return this.catsRepository.find({ name });
}
}