nest中TypeORM的使用(一)

  |  

文档

postgreSql

数据库初始化连接

配置不同环境导入配置
在 app.module.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { ConfigModule, ConfigService } from "@nestjs/config";
import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import customConfig from "./config/index";
import { EntityModule } from "./entity/entity.module";

@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true, // 作用于全局
load: [customConfig], // 加载自定义配置项
}),
TypeOrmModule.forRootAsync({
imports: [ConfigModule], // 数据库配置项依赖于ConfigModule,需在此引入
useFactory: (configService: ConfigService) =>
configService.get("database"),
inject: [ConfigService], // 记得注入服务,不然useFactory函数中获取不到ConfigService,
}),
// TypeOrmModule.forRoot({
// type: 'postgres',
// host: 'localhost',
// port: 5432,
// username: 'postgres',
// password: '123456',
// database: 'test',
// logging: true, // 打印sql
// autoLoadEntities: true, // 自动加载实体
// synchronize: true, // 同步数据库表字段
// }),
EntityModule,
],
controllers: [],
providers: [],
})
export class AppModule {}

在 config/index.ts

1
2
3
4
5
6
7
8
9
10
11
12
import dev from "./dev";
import api from "./api";

const configs = {
development: dev,
production: api,
};

const env = process.env.NODE_ENV || "development";

console.log("env=============>", env);
export default () => configs[env];

在 config/dev.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
export default {
database: {
type: "postgres",
host: "localhost",
port: 5432,
username: "postgres",
password: "123456",
database: "test",
logging: true, // 打印sql
autoLoadEntities: true, // 自动加载实体
synchronize: false, // 同步数据库表字段
},
};

model 表映射

在 entity/entity.module.ts

1
2
3
4
5
6
7
8
9
10
import { Module, Global } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { Admin } from "./Admin.entity";

@Global()
@Module({
imports: [TypeOrmModule.forFeature([Admin])],
exports: [TypeOrmModule],
})
export class EntityModule {}

在 Admin.entity.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import {
Entity,
Column,
PrimaryGeneratedColumn,
Index,
CreateDateColumn,
UpdateDateColumn,
DeleteDateColumn,
} from "typeorm";

@Entity("admin")
export class Admin {
@PrimaryGeneratedColumn()
id: number;

@Column()
name: string;

@Index()
@CreateDateColumn({ type: "timestamptz" })
createTime: Date;

@UpdateDateColumn({ type: "timestamptz" })
updateTime: Date;

@DeleteDateColumn({ select: false, type: "timestamptz" })
deleteTime: Date;
}

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { Injectable, Dependencies } from '@nestjs/common';
import { getRepositoryToken, InjectRepository } from '@nestjs/typeorm';
import { Admin } from '../../entity/Admin.entity';
import { EntityRepository, Repository } from 'typeorm';

// 第二种写法
@Injectable()
export class AdminService {
constructor(
@InjectRepository(Admin)
private repository: Repository<Admin>,
) {}

// 分页查询
async findAndCount({ limit, offset, order = {}, where = {} }) {
return this.repository.findAndCount({
skip: offset,
take: limit,
where,
order,
});
}
// 新增
async insert(data) {
return this.repository.insert(data);
}
// 查询一条数据
async findOne(id) {
return await this.repository.findOne({
where: {
id,
},
});
}
// 修改数据
async update(id: number, data) {
return this.repository.update(id, data);
}
// 删除
async delete(id: number) {
return this.repository.delete({
id,
});
}
// 软删除
async softDelete(id: number) {
return this.repository.softDelete({
id,
});
}
// 软删除还原
async restore(id: number) {
return this.repository.restore({
id,
});
}
}

连接多个数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
TypeOrmModule.forRootAsync({
name: 'qbit-aml',
imports: [ConfigModule], // 数据库配置项依赖于ConfigModule,需在此引入
useFactory: (configService: ConfigService) => configService.get('DATABASE_CONFIG')[0],
inject: [ConfigService], // 记得注入服务,不然useFactory函数中获取不到ConfigService,
}),
TypeOrmModule.forRootAsync({
name: 'qbit-core',
imports: [ConfigModule], // 数据库配置项依赖于ConfigModule,需在此引入
useFactory: (configService: ConfigService) => configService.get('DATABASE_CONFIG')[1],
inject: [ConfigService], // 记得注入服务,不然useFactory函数中获取不到ConfigService,
}),


TypeOrmModule.forFeature([QbitNotification], 'qbit-aml'),
TypeOrmModule.forFeature([Account, AccountUser], 'qbit-core'),



@InjectRepository(Account, 'qbit-core') private readonly accountRepo: Repository<Account>,

nest-typeorm
typeorm

文章目录
  1. 1. 文档
  2. 2. 数据库初始化连接
  3. 3. model 表映射
  4. 4. 使用