Lesson 17 / 34
Relationships (One-to-Many, Many-to-Many)
Model one-to-many and many-to-many relations with TypeORM decorators and load related data deliberately.
One-to-Many example
A User has many Posts—use @OneToMany() and @ManyToOne() decorators.
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@OneToMany(() => Post, post => post.user, { cascade: true })
posts: Post[];
}
@Entity()
export class Post {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@ManyToOne(() => User, user => user.posts)
user: User;
}Eager vs Lazy loading
Relations are not loaded by default. Fetch them with the relations option or leftJoinAndSelect(), and use eager: true sparingly.