-
Notifications
You must be signed in to change notification settings - Fork 230
/
database.service.ts
executable file
·79 lines (66 loc) · 2.34 KB
/
database.service.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { Injectable } from '@nestjs/common';
import { InjectEntityManager, InjectRepository } from '@nestjs/typeorm';
import { EntityManager, Repository } from 'typeorm';
import { Sampletable1 } from '#entity/sampledb1';
import { Sampletable2 } from '#entity/sampledb2';
/**
* Database Query Execution Example
*/
@Injectable()
export class DatabaseService {
private tablerepo: Repository<Sampletable1>;
constructor(
/**
* Sample1
* https://typeorm.io/#/working-with-repository
* https://typeorm.io/#/repository-api
* Need TypeOrmModule.forFeature([]) imports
*/
@InjectRepository(Sampletable1)
private sampletable1: Repository<Sampletable1>,
/**
* Sample2
* https://typeorm.io/#/working-with-entity-manager
* https://typeorm.io/#/entity-manager-api
*/
@InjectEntityManager()
private manager: EntityManager,
) {
/**
* Sample3
* https://typeorm.io/#/entity-manager-api - getRepository
*/
this.tablerepo = this.manager.getRepository(Sampletable1);
}
/**
* https://typeorm.io/#/find-options
*/
public async sample1(): Promise<Sampletable1[]> {
// Repository
return this.sampletable1.find();
}
public async sample2(): Promise<Sampletable1[]> {
// EntityManager
return this.manager.find(Sampletable1);
}
public async sample3(): Promise<Sampletable1[]> {
// EntityManagerRepository
return this.tablerepo.find();
}
/**
* https://typeorm.io/#/select-query-builder
*/
public async joinQuery(): Promise<boolean> {
await this.sampletable1
.createQueryBuilder('tb1')
.innerJoin('sampletable2', 'tb2', 'tb2.id = tb1.id') // inner or left
.select(['tb1', 'tb2.title'])
.where('tb1.id = :id', { id: 123 })
.getRawOne(); // getOne, getMany, getRawMany ...
await this.sampletable1.createQueryBuilder('tb1').innerJoinAndSelect('sampletable2', 'tb2', 'tb2.id = tb1.id').getOne();
await this.sampletable1.createQueryBuilder('tb1').leftJoinAndSelect(Sampletable2, 'tb2', 'tb2.id = tb1.id').getRawMany();
await this.sampletable1.createQueryBuilder('tb1').leftJoinAndMapOne('tb1.tb2row', 'sampletable2', 'tb2', 'tb2.id = tb1.id').getOne();
await this.sampletable1.createQueryBuilder('tb1').leftJoinAndMapMany('tb1.tb2row', Sampletable2, 'tb2', 'tb2.id = tb1.id').getMany();
return true;
}
}