Ember.js: Load related multiple models

311 views Asked by At

Since the ember-guides explains how to load mutliple models on a route like that

export default Ember.Route.extend({
  model() {
    return Ember.RSVP.hash({
      songs: this.get('store').findAll('song'),
      albums: this.get('store').findAll('album')
    });
  }
});

Im wondering how to load only the related model-entries from a second one, like loading ALL songs but only the albums which are indexed in the songs if we assume that the song model containing this

...
albums: hasMany('album'),
...

How can I do that?

2

There are 2 answers

0
Max Wallace On

Assuming your adapter and JSON API backend support it, you can simply say:

export default Ember.Route.extend({
  model() {
    return Ember.RSVP.hash({
      songs: this.get('store').findAll('song', { include: 'albums' }),
    });
  }
});

Typically, this will generate a GET to /songs?include=albums, which tells the JSON API backend to include the related album resources, according to http://jsonapi.org/format/#fetching-includes.

On the Ember side of things, this feature is documented at http://emberjs.com/blog/2016/05/03/ember-data-2-5-released.html#toc_code-ds-finder-include-code.

If the above isn't an option, then there's no way to load everything in one request without building a custom endpoint and using store.pushPayload.

2
vinay pandey On

Here is one way to do it

export default Ember.Route.extend({
  model() {
    var promise = new Ember.RSVP.Promise(function(resolve,reject){
      this.store.findAll('song').then(function(songs){
        var albumPromises = songs.map(fuction(s){return s.get('album')});
        Em.RSVP.all(albumPromises).then(function(){
           resolve(songs);
        });
      });
    });
    return promise;
  }
});

So Basically you are waiting till everything is resolved.

Hope it helps!