# typeorm (opens new window)
- 安装依赖
npm i @nestjs/typeorm typeorm mysql2
- 在 app.modules 中导入
// ...
import { TypeOrmModule } from '@nestjs/typeorm'
@Module({
imports: [
TypeOrmModule.forRoot({
"type": "mysql",
"host": "localhost",
"port": 3306,
"username": "root",
"password": "Root@132",
"database": "test",
"entities": [
"dist/**/*.entity{.ts,.js}"
],
"synchronize": true
})
]
})
- 定义实体类 Entity
import { Entity, PrimaryColumn, Column } from 'typeorm'
@Entity()
export class User {
@PrimaryColumn()
id: number
@Column()
name: string
}
- 到需要引用的模块注入
// ...
import { User } from './entities/user.entity'
import type { Repository } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'
@Injectable()
export class UserService {
constructor(
@InjectRepository(User)
private readonly user: Repository<User>
)
async getDetail(id: number): Promise<any[]> {
// 使用注入的类进行操作
return this.user.query('select * from test')
}
}
- 去引用到的模块的 module 注册
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './entities/user.entity'
@Module({
imports: [
TypeOrmModule.forFeature([User])
]
})