Lesson 17 / 33

Relationships (One-to-Many, Many-to-Many)

Model entity relationships using TypeORM decorators.

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

By default, relations are lazy—fetch them with leftJoinAndSelect(). Use eager: true to auto-load (sparingly).