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 makestrack.albumthe album whose id is intrack.albumId. The key's name comes from the relationship's:albumreadsalbumId.tracks: Puzzle.hasMany('track')on an album makesalbum.tracksevery track whosealbumIdis this album's id. The key's name comes from the owner's type:albumagain.
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
- In
track.js, addalbum: Puzzle.belongsTo('album')and a getter that prints a track's length,241seconds as4:01:
get length() {
const minutes = Math.floor(this.seconds / 60);
const seconds = String(this.seconds % 60).padStart(2, '0');
return `${minutes}:${seconds}`;
}
- In
album.js, addtracks: Puzzle.hasMany('track'). - 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.