Posts TypeORM CheatSheet
Post
Cancel

TypeORM CheatSheet

Setting up TypeORM: Cheatsheet


[TOC]

Connect with database


1
2
3
4
5
6
7
8
9
10
11
12
const conn = await createConnection({
  type: "postgres",
  host: "",
  port: 5432,
  database: "exmapleschema", // database name
  username: "postgres", // username
  password: "docker", // password
  entities: [User], // Entity
  synchronize: true, // sync changes
  logging: true,
  logger: "file",
});

Create Entity an Relation ships


To create an entity you need to create a class and decorate its field with decorators

  • Entity
  • Column

One to One

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
import {Entity, PrimaryGeneratedColumn, Column, ManyToOne} from "typeorm";



@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

  	//@JoinColumn which is required and must be set only on one side of the relation. The side you set 	@JoinColumn on, that side's table will contain a "relation id" and foreign keys to target entity table.
    @OneToOne(type => Profile)
    @JoinColumn()
    profile: Profile;

  	// This is if you need the id when using query builder
  	@PrimaryColumn()
    profileId: int

}

+-------------+--------------+----------------------------+
|                        profile                          |
+-------------+--------------+----------------------------+
| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |
| gender      | varchar(255) |                            |
| photo       | varchar(255) |                            |
+-------------+--------------+----------------------------+

+-------------+--------------+----------------------------+
|                          user                           |
+-------------+--------------+----------------------------+
| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |
| name        | varchar(255) |                            |
| profileId   | int(11)      | FOREIGN KEY                |
+-------------+--------------+----------------------------+


One to Many / Many to One

One to many - cannot exist on its own. You need to define many to one and the Entity will have foreign key

Many to one - Can be on its own and will have the foreign key

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
@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @OneToMany(type => Photo, photo => photo.user)
    photos: Photo[];

}

@Entity()
export class Photo {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    url: string;

    @ManyToOne(type => User, user => user.photos)
    user: User;

}

//You can omit @JoinColumn in a @ManyToOne / @OneToMany relation. @OneToMany cannot exist without @ManyToOne. If you want to use @OneToMany, @ManyToOne is required.
//However, the inverse is not required: If you only care about the @ManyToOne relationship, you can define it without having @OneToMany on the related entity.
//Where you set @ManyToOne - its related entity will have "relation id" and foreign key.

+-------------+--------------+----------------------------+
|                         photo                           |
+-------------+--------------+----------------------------+
| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |
| url         | varchar(255) |                            |
| userId      | int(11)      | FOREIGN KEY                |
+-------------+--------------+----------------------------+

+-------------+--------------+----------------------------+
|                          user                           |
+-------------+--------------+----------------------------+
| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |
| name        | varchar(255) |                            |
+-------------+--------------+----------------------------+

Many to Many

Creating many to many relationship with additional table

  • You can make relation by your self by assigning ID to it
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
@Entity()
export class Category {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

		@OneToMany(type => PostToCategory, postToCategory => postToCategory.category)
		public postToCategories!: PostToCategory[];

}


@Entity()
export class Post {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    title: string;

    @Column()
    text: string;

		@OneToMany(type => PostToCategory, postToCategory => postToCategory.post)
		public postToCategories!: PostToCategory[];
}

@Entity()
export class PostToCategory {
    @PrimaryGeneratedColumn()
    public postToCategoryId!: number;

    @Column()
    public postId!: number;

    @Column()
    public categoryId!: number;

    @Column()
    public order!: number;

    @ManyToOne(type => Post, post => post.postToCategories)
    public post!: Post;

    @ManyToOne(type => Category, category => category.postToCategories)
    public category!: Category;
}

+-------------+--------------+----------------------------+
|                     PostToCategory                      |
+-------------+--------------+----------------------------+
| id          | int(11)      | PRIMARY KEY AUTO_INCREMENT |
| categoryId  | int(11)      | FOREIGN KEY                |
| postId      | int(11)      | FOREIGN KEY                |
+-------------+--------------+----------------------------+
This post is licensed under CC BY 4.0 by the author.