Relations & QueryBuilder

Preview — 3 of 10 questions

A User has many Posts and each Post belongs to one User. How should the relation be declared on both sides?

javascript
import { Entity, PrimaryGeneratedColumn, OneToMany, ManyToOne } from 'typeorm';

@Entity()
export class User {
  @PrimaryGeneratedColumn() id: number;
  @OneToMany(() => Post, (post) => post.author)
  posts: Post[];
}

@Entity()
export class Post {
  @PrimaryGeneratedColumn() id: number;
  @ManyToOne(() => User, (user) => user.posts)
  author: User; // FK column lives here
}
A@OneToMany on both User.posts and Post.user
B@ManyToOne on User.posts and @OneToMany on Post.user
C@OneToMany(() => Post, p => p.user) on User.posts and @ManyToOne(() => User, u => u.posts) on Post.user
DOnly @OneToMany on User.posts; the inverse is unnecessary

For a @ManyToMany relation between Challenge and Tag, what is the role of @JoinTable()?

javascript
import { Entity, PrimaryGeneratedColumn, ManyToMany, JoinTable } from 'typeorm';

@Entity()
export class Challenge {
  @PrimaryGeneratedColumn() id: number;

  @ManyToMany(() => Tag, (tag) => tag.challenges)
  @JoinTable() // owning side -> creates challenge_tags_tag
  tags: Tag[];
}

@Entity()
export class Tag {
  @PrimaryGeneratedColumn() id: number;
  @ManyToMany(() => Challenge, (c) => c.tags)
  challenges: Challenge[];
}
AIt must be placed on both sides to create two join tables
BIt converts the relation into a one-to-many
CIt is optional and only affects naming
DIt marks the owning side and tells TypeORM to create the single join (junction) table

What distinguishes an eager: true relation from a lazy (Promise-typed) relation in TypeORM?

javascript
@Entity()
export class Order {
  @PrimaryGeneratedColumn() id: number;

  // Eager: always loaded
  @ManyToOne(() => Customer, { eager: true })
  customer: Customer;

  // Lazy: loaded on await
  @OneToMany(() => Item, (i) => i.order, { lazy: true })
  items: Promise<Item[]>;
}

const order = await orderRepo.findOneBy({ id: 1 });
const items = await order.items; // lazy fetch here
AEager relations require a separate query call, lazy relations are always joined
BEager relations are loaded automatically on every find, while lazy relations are typed as Promise and loaded only when awaited
CThey are identical at runtime
DLazy relations are loaded automatically and eager ones must be requested

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.