Intermediate Phase Seven - Fetching Related Records (Eager & Lazy Loading)

Understand the Problem

We want to fetch Trees alongside their related Insects (and vice versa) using Sequelize. For one route, we’ll use eager loading with include, and for the other, we’ll demonstrate lazy loading.

Devise a Plan

  1. Add a route for /trees-insects that uses eager loading: Tree.findAll({ include: Insect }) with only specific attributes in Insect and sorting.
  2. Filter out trees without related insects if required.
  3. Add a route for /insects-trees that fetches insects first, then uses lazy loading with something like insect.getTrees().
  4. Return the minimal attributes needed for trees in the final JSON.

Carry Out the Plan (Solution)

File Name & Location: server/routes/joined.js

// Eager loading approach example (trees-insects):
// GET /trees-insects
// 1. const treesWithInsects = await Tree.findAll({
//      include: [{
//        model: Insect,
//        attributes: ['id','name'],
//        through: { attributes: [] }, // omit join table columns
//        order: [['name','ASC']]
//      }]
//    });
// 2. Optionally filter out any tree that has no insects

// Lazy loading approach example (insects-trees):
// GET /insects-trees
// 1. const insects = await Insect.findAll({ ... });
// 2. for each insect, call insect.getTrees({ attributes: ['id','tree'] })
// 3. combine results into a final JSON object to send
    

Expected Input: GET requests to /trees-insects or /insects-trees.

Expected Output: Arrays of objects with nested arrays of related items, each limited to certain attributes.

Elementary (Basic) Approach

Advanced Approach

Step-by-Step Directions:

  1. Set up your associations properly (previous phases).
  2. In joined.js, create /trees-insects using findAll with include.
  3. Implement optional filters or attribute selection.
  4. Create /insects-trees with a loop or map, calling insect.getTrees() for each record.
  5. Return the aggregated result as JSON.

Explanations & Analogies: Eager loading is like checking out a library book and automatically bringing along the shelf info. Lazy loading is when you first get the book details, then go back and request the shelf data only if you need it.

Real World Example: If your user interface always needs the related data, eager load it. If you only show details on demand, lazy load can reduce initial overhead.

Look Back

Run your tests or check the JSON responses. Confirm that the data includes only the desired fields and that missing associations are handled properly.