Relationships

Every album has tracks. A new Track model is registered, and fixtures.js now seeds four tracks for each album, each one pointing at its album through an albumId field. That field is a foreign key: it holds the id of the record the track belongs to.

Relationships turn foreign keys into properties:

  • album: Puzzle.belongsTo('album') on a track makes track.album the album whose id is in track.albumId. The key's name comes from the relationship's: album reads albumId.
  • tracks: Puzzle.hasMany('track') on an album makes album.tracks every track whose albumId is this album's id. The key's name comes from the owner's type: album again.

Each read is a fresh look in the store. A relationship never fetches: once Music has a server, album.tracks still only sees tracks already loaded. So a view that needs related records asks for them by foreign key in data(), the way findMany with a filter does below. That is the read the store can fetch, and it subscribes the view too.

A model is a class, so it can carry plain getters. A getter works anywhere the record is read, templates included.

Your turn

  1. In track.js, add album: Puzzle.belongsTo('album') and a getter that prints a track's length, 241 seconds as 4:01:
get length() {
  const minutes = Math.floor(this.seconds / 60);
  const seconds = String(this.seconds % 60).padStart(2, '0');
  return `${minutes}:${seconds}`;
}
  1. In album.js, add tracks: Puzzle.hasMany('track').
  2. In Album.pzl, find the album's tracks by its id and list them with their lengths:
tracks: store.findMany('track', { filter: (track) => track.albumId === params.id }),

The track titles are generated test data, so expect made-up words.

Chapters