Ember 2.x在该模型的子路径中获得模型的关系

时间:2016-01-26 15:59:52

标签: ember.js ember-data

想象一下,我有两个模型,作者和书。

// models/author.js
DS.Model.extend({
  name: DS.attr(),
  books: DS.hasMany('book')
});


// models/book.js
DS.Model.extend({
  title: DS.attr(),
  author: DS.belongsTo('author')
})

有一个端点就好了 /api/authors/{authorID}/books能够在一个批处理请求中获取所有作者的书籍,而不是多次调用/api/books/{bookID},但似乎ember不支持这一点。可以执行/api/books?authorID={authorID},但这会失去store的一些好处。

是否有一种Ember习惯的方式/api/authors/{authorID}/books?同样,目标是能够为作者制作一个批量请求以获取所有书籍,而不是为作者hasMany列表中的每本书打一个电话。

对于更多上下文,我有以下路由结构:

// router.js
...
this.route('authors', function() {
  this.route('author', { path: ':id' }, function() {
    this.route('books');
  });
});
...

在作者'路线我将加载所有作者。我不想同步加载他们的相关书籍,但由于列表可能很大而且没有在这条路线上使用。

author路线中,我使用已检索作者的数据(在本例中为名称)。

books路线中,我希望最终加载所有作者的相关书籍,而无需每本书发送一个请求。

2 个答案:

答案 0 :(得分:1)

RestAdapter,但它很难看。然后查询为typedef struct mystruct_t{ int field1; const char *field2; }mystruct_t; 。但是,如果你知道你需要所有作者的书籍,你可以侧载它们,当你打电话给const mystruct_t mystruct={.field1=23, .field2="myname" }; myfunc(&mystruct); 时,它不会再触发取得。

答案 1 :(得分:1)

如果您在图书路线中使用modelFor(),则可以get()为单个作者提供图书。

作者作者路线

model(params) {
  return this.store.find('author', params.id); 
}

作者作者书籍路线

model() {
  var author = this.modelFor('authors.show');
  return author.get('books');
}

这是一个余烬:https://ember-twiddle.com/924dd7d31e0984b708f9