Relations & QueryBuilder — Series 3

Preview — 3 of 10 questions

What does placing @JoinColumn() on Profile decide?

javascript
@Entity() export class User {
  @OneToOne(() => Profile, (p) => p.user) profile: Profile;
}

@Entity() export class Profile {
  @OneToOne(() => User, (u) => u.profile)
  @JoinColumn()
  user: User;
}
AThat both tables carry a foreign key pointing at each other
BThat profile holds the foreign-key column (userId), making it the owning side — so the link is written when a profile is saved, and User has no column for the relation at all
CThat the relation is loaded eagerly from Profile
DThat a join table is created between the two

What should you expect when reading a deep hierarchy?

javascript
@Entity()
export class Category {
  @ManyToOne(() => Category, (c) => c.children, { nullable: true })
  parent: Category | null;

  @OneToMany(() => Category, (c) => c.parent)
  children: Category[];
}
ATypeORM loads the whole tree automatically, since both sides are declared
BSelf-references are rejected because the entity would be circular
COnly the immediate parent can ever be loaded
DA single relations: { children: true } loads one level only — each additional level needs another query, so a deep tree becomes a recursive fetch; a recursive CTE, or a tree structure such as materialised paths or nested sets, is what answers "the whole subtree" in one query

How should this be modelled?

javascript
A user joins a team with a role and a joined-at date.
AAs an explicit join entity — TeamMembership with @ManyToOne to both sides plus its own role and joinedAt columns — because an implicit @ManyToMany join table has room only for the two foreign keys
BAs a @ManyToMany with the extra fields declared on one of the two entities
CAs a @ManyToMany with @JoinTable({ extraColumns: [...] })
DAs two separate @OneToMany relations with the data duplicated on each side

Sign up free to play

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