Fetch relations automatically


#1

Hi, I have two related models (Notification):

import DS from 'ember-data';
import MF from 'ember-data-model-fragments';

export default DS.Model.extend({
    type: DS.attr('string'),
    status: DS.attr('string'),
    details: DS.attr(),
    createdAt: DS.attr('date'),
    updatedAt: DS.attr('date'),
    ...
    document: DS.belongsTo('document')
});

Here is the Document model:

        import DS from 'ember-data';
        import MF from 'ember-data-model-fragments';

export default DS.Model.extend({
    type: DS.attr('string'),
    category: DS.attr('string'),
    number: DS.attr('string'),
    valid: MF.fragment('doc-valid'),
   ....
    details: MF.fragment('doc-details'),
	user: DS.belongsTo('user'),
    vehicle: DS.belongsTo("vehicle"),
});

What I want to do is when them model is fetching notification I want to also fetch related documents by making additional requests for each of them.

I have tried { async: false }, but is not working.

E.g. this.store.findAll('notification) should result in notifications with documents. For each document a new request should be made automatically and then model should be ready only when all requests are ready.

Is possible?


#2

Something like this in your route should do the trick

model() {
  return this.store.findAll('notifcation').then(function(notifcations) {
    const promises = notifcations.map(function(n) {
      retrun n.get('document');
    });

    return Ember.RSVP.all(promises);
  })
}

Let me know if this works for you or if it’s not clear!

Cheers, Ben


#3

Hi, This works, but I want my model to be an array of notifications, in this case I suppose it will be an array of documents.


#4
return Ember.RSVP.all(promises).then(function() {
  return notifcations;
});

:wink:


#5

Thanks, this will do.