-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
Copy pathjoins.ts
93 lines (75 loc) · 2.52 KB
/
joins.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import { Entity, PrimaryGeneratedColumn, Column, Connection, BaseEntity, LessThan, DeleteDateColumn, OneToMany, ManyToOne } from "typeorm";
import { newDb } from '../../src/db';
import { expect } from 'bun:test';
@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn({ type: 'integer' })
id!: number;
@Column({ type: 'text' })
name!: string;
@OneToMany(type => Photo, photo => photo.user)
photos!: Photo[];
}
@Entity()
export class Photo extends BaseEntity {
@PrimaryGeneratedColumn({ type: 'integer' })
id!: number;
@Column({ type: 'text' })
url!: string;
@ManyToOne(type => User, user => user.photos)
user!: User;
}
export async function typeormJoinsSample() {
//==== create a memory db
const db = newDb({
// 👉 Recommended when using Typeorm .synchronize(), which creates foreign keys but not indices !
autoCreateForeignKeyIndices: true,
});
//==== create a Typeorm connection
const got: Connection = await db.adapters.createTypeormConnection({
type: 'postgres',
entities: [User, Photo]
});
try {
//==== create tables
await got.synchronize();
const users = got.getRepository(User);
const photos = got.getRepository(Photo);
//==== create entities
await users.create({
name: 'me',
photos: [
await photos.create({ url: 'photo-of-me-1.jpg' }).save(),
await photos.create({ url: 'photo-of-me-2.jpg' }).save(),
]
}).save();
await users.create({
name: 'you',
photos: [
await photos.create({ url: 'photo-of-you-1.jpg' }).save(),
await photos.create({ url: 'photo-of-you-2.jpg' }).save(),
]
}).save();
//==== query entities
const user = await users.createQueryBuilder('user')
.leftJoinAndSelect('user.photos', 'photo')
.where('user.name = :name', { name: 'me' })
.getOne();
expect(user).toEqual({
id: 1,
name: 'me',
photos: [{
id: 1,
url: 'photo-of-me-1.jpg'
}, {
id: 2,
url: "photo-of-me-2.jpg"
}]
} as any)
} finally {
// do not forget to close the connection once done...
// ... typeorm stores connections in a static object,
// and does not like opening 'default connections.
await got.close();
}
}