पाठ 17 / 34

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

TypeORM decorators से one-to-many और many-to-many relations model करें और संबंधित data जानबूझकर load करें।

One-to-Many उदाहरण

एक User के पास many Posts हैं—@OneToMany() और @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 बनाम Lazy loading

Relations default रूप से load नहीं होते। उन्हें relations option या leftJoinAndSelect() से लाएँ, और eager: true कम उपयोग करें।