Search code examples
ember.jsember-datajson-api

Ember data bulk fetch async hasMany relationship records


I'd like to know whether it is possible to configure Ember data in a way that async hasMany relationships are loaded in a single request.

Given the following model:

// models/post.js
export default DS.Model.extend({
  comments: DS.hasMany()
});

// models/comments.js
export default DS.Model.extend({
  ...
});

When I reference the property comments somewhere in the template or controller, it will fetch the related comments of the post one-by-one in separate requests. This results in many requests and I'd like to combine those into a single request with a filter on id-property.


Solution

  • There is a switch you have to enable for the desired behaviour called coalesceFindRequests: true that you can set in you application adapter like so:

    // adapters/application.js
    import DS from 'ember-data';
    
    export default DS.RESTAdapter.extend({
        coalesceFindRequests: true,
    });
    

    Now Ember will fetch multiple records of known id via ..api/comments?ids[]=1&ids[]=2

    I suppose it'll be the same for a JSONAdapter.