简体   繁体   中英

Loading associated models in Ember.js

I have related models Track and Milestone as follows:

App.Track = DS.Model.extend({
  title: DS.attr('string'),
  description: DS.attr('string'),
  milestones: DS.hasMany('milestone', {
    async: true
  })
});

App.Milestone = DS.Model.extend({
  track: DS.belongsTo('track'),
  title: DS.attr(),
  description: DS.attr(),
});

Now, I would like to lazy load the milestones for a track. I believe the default expectation of Ember data is that the response returned by the endpoint returning track also contains an array of milestone ids, ie. something like :

GET: /tracks/1

{
    "title": "My track",
    "description": "lorem ipsum dolor sit amet",
    "milestones": [1,2,3]
}

My backend is a relational database, and I would like to avoid joining tracks and milestones unless necessary.

So my expectation would be that even if the response returned by tracks endpoint contains no milestones array, the following should make a request to /tracks/1/milestones and associate the obtained milestones with the relevant track.

 this.store.find('track', params.track_id).then(function(track) {
  return track.get('milestones').then(function(milestones) {
    return console.log(milestones);
  });
});

The above snippet is inside a Route#model method.

Is it feasible to accomplish this using Ember Data ? If not then can I use some other persistence library for Ember ? Please don't suggest using $.ajax directly.

Ember-Data's REST Adapter roughly follows the JSON API standard, both URL and ID based. It sounds like what you want is URL based loading. Take a look at an example in the REST Adapter documentation . This will lazy-load both the records and the IDs for the records.

The way you are returning your JSON for tracks, Ember-Data will use the findMany method and request GET: /milestones?ids[]=1&ids[]=2&ids[]=3 .

If you want Ember Data to instead request GET: /tracks/1/milestones (using the findHasMany method), you'll need to format your tracks JSON with a links property like so

{
    "title": "My track",
    "description": "lorem ipsum dolor sit amet",
    "links": { "milestones": "/tracks/1/milestones" }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM