Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 ยท Relations

Loading Strategies and Cascades

Load relations with TypeORM relations and Sequelize include, choose join or separate queries, understand eager and lazy loading, avoid N+1 queries, and use cascade options safely.

Defining a relation is half the job. The other half is deciding when and how related rows are loaded, and what happens to them when the parent is saved or deleted. Get this wrong and a page that should run two queries runs two hundred.

Library code is read-only; the stand-ins count queries so you can see the difference.

Explicit loading: the default you want

Neither library loads relations unless you ask. That is a good default.

TypeScript
// TypeORM
await authors.find({ relations: { posts: true } });
await authors.find({ relations: { posts: { comments: true } } });           // nested
await authors.find({ where: { posts: { published: true } }, relations: { posts: true } });  // filter by related

// Sequelize
await Author.findAll({ include: [Post] });
await Author.findAll({ include: [{ model: Post, as: "posts", include: [Comment] }] });
await Author.findAll({ include: [{ model: Post, as: "posts", where: { published: true }, required: false }] });

Details worth knowing:

  • In Sequelize, include with a where becomes an INNER JOIN (required: true) by default, so authors without matching posts disappear. Set required: false for a LEFT JOIN that only filters the included posts.
  • In TypeORM, a where on a relation inside find filters the parent rows by that condition.
  • TypeORM can also select relation columns with select: { posts: { title: true } }; Sequelize uses attributes inside the include.

One JOIN or several queries?

A JOIN returns one wide result where parent columns repeat for every child row. For a single one-to-many that is fine; for several collections at once the row count multiplies (3 posts x 4 tags = 12 rows per author). The alternative is separate queries.

TypeScript
// TypeORM: choose per query (or globally in the DataSource)
await authors.find({ relations: { posts: true }, relationLoadStrategy: "query" });   // "join" is the default

// Sequelize: separate: true on a hasMany include runs a second query
await Author.findAll({ include: [{ model: Post, as: "posts", separate: true }] });

Rule of thumb: JOIN for one-to-one and many-to-one; separate queries for several or large one-to-many collections, and when you paginate parents (a JOIN with LIMIT would cut the joined rows, not the parents; Sequelize handles it with a subquery, TypeORM with take/skip instead of limit/offset).

Eager and lazy relations

Eager relations load automatically with every find.

TypeScript
// TypeORM
@OneToMany(() => Post, (p) => p.author, { eager: true })
posts!: Post[];

Eager loading works with find* methods but is ignored by the QueryBuilder, and it makes every query heavier, even where you do not need the data. It is easy to start and hard to undo; prefer explicit relations for most code and reserve eager for small, always-needed relations such as a role.

Lazy relations (TypeORM) are promises: const posts = await author.posts;. They require typing the property as Promise<Post[]> and loading on first access. Lazy loading hides queries, which makes N+1 easy to introduce, so many teams avoid it. Sequelize has no lazy properties; you call await author.getPosts() yourself, which makes each query visible.

The N+1 problem

Loading a list and then querying inside a loop is the classic mistake: 1 query for the list plus N queries for the children.

Node.js Counting queries

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Turn on query logging in development (logging: true in TypeORM, logging: console.log in Sequelize) and watch for repeating statements. The performance chapter returns to this with batching tools.

Cascades

A cascade makes an operation on the parent apply to its children in the ORM, in one call.

TypeScript
// TypeORM: cascade on the relation
@OneToMany(() => Post, (post) => post.author, { cascade: ["insert", "update"] })
posts!: Post[];

await authors.save({ name: "Ana", posts: [{ title: "One" }, { title: "Two" }] });   // inserts author and posts

cascade: true means insert, update, remove, soft-remove and recover. Be selective: cascade: ["remove"] on a parent means repository.remove(author) removes the posts too.

Two separate concepts hide behind the word "cascade":

Where Option Who deletes the children
ORM TypeORM cascade: ["remove"]; Sequelize hooks: true with onDelete: "CASCADE" The ORM, with extra statements
Database onDelete: "CASCADE" on the foreign key The database, in the same DELETE

The database-level rule is more reliable: it also fires for raw SQL, delete() and other programs. Use onDelete for deletion and ORM cascade for convenient nested saving.

TypeORM also offers orphanedRowAction: "delete" on the many-to-one side, so removing a post from author.posts and saving deletes the orphan row.

Sequelize creates nested rows through include in create:

TypeScript
await Author.create(
  { name: "Ana", posts: [{ title: "One" }, { title: "Two" }] },
  { include: [{ model: Post, as: "posts" }] }
);
Node.js Nested save in one call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the transaction around the nested save: if the second child failed, the author would not remain. Both ORMs wrap cascaded saves in a transaction for the same reason, and the Transactions chapter shows how to control it yourself.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the N+1 problem?

    The query count grows with the list size; batching or JOINs fix it.
  2. 2. In Sequelize, what happens when an include has a where clause and nothing else?

    required defaults to true when where is set; use required: false to keep the parents.
  3. 3. Why do many teams avoid eager and lazy relations?

    Explicit relations or include make loading visible and intentional.
  4. 4. Which cascade is more reliable for deleting children?

    The database applies it for every program and every delete, including raw SQL.

Summary

  • Load relations explicitly with relations (TypeORM) or include (Sequelize).
  • Choose JOINs for to-one relations; use separate queries for large or multiple collections and when paginating.
  • Eager and lazy relations are convenient but hide queries; use them sparingly.
  • N+1 is a loop of queries; batch with IN (...) or a JOIN and watch the query log.
  • Use ORM cascade for nested saves and database onDelete rules for deletes.

Next: Why You Need Migrations