如何在Ember路线中获取资源的关系?

时间:2016-10-14 16:40:49

标签: ember.js ember-data

我在Ember路线中有这个代码:

let forum = this.store.findRecord('forum', 'main').then(function(forum) {
  console.log('FORUM:', forum);
  let categories = forum.get('categories');
  console.log('CATEGORIES:', categories);
});

return forum;

此控制台返回:

  

FORUM:Object {store:Object,_internalModel:Object,id:Getter,   currentState:Object,isError:false,adapterError:null,OWNER   [id = __ ember1476462923058714220863537]:对象,_超级:ROOT(),还有2个......   }

     

类别:未定义

很明显,向/forums/main提出了请求,但之后没有提出任何要求。 forum.get('categories')的作用是什么?我怎么能得到资源的关系?不应该请求/forums/main/categories

论坛:

export default DS.Model.extend({
  // Attributes
  language: DS.attr('string'),

  // Relationships
  categories: DS.hasMany('category', { async: true }),
});

类别:

export default DS.Model.extend({
  // Attributes
  name: DS.attr('string'),

  // Relationships
  forum: DS.belongsTo('forum', { async: true }),
  boards: DS.hasMany('board', { async: true })
});

路由器(相关部分):

this.route('community', function() {
  this.route('players');
  this.route('forum', function() {
  });
});

1 个答案:

答案 0 :(得分:1)

为了在向categories(同步请求)发出请求时获取forumforumcategory模型之间的关系需要正确配合建立:

模型/ forum.js

App.Forum = DS.Model.extend({
  categories: DS.hasMany('categories');
});

模型/ category.js

App.Category = DS.Model.extend({
  forum: DS.belongsTo('forum', { async: false });
});

一旦您的承诺得到解决,您可能还希望获得categories。在这种情况下,您可以执行以下操作:

this.store.findRecord('forum', 'main').then((function(_this) {
  return function(forum) {
    console.log(JSON.stringify('forum: ' + forum));
    let categories = _this.store.find('category', forum.get('category_id'));
  };
})(this));

如果可以,我建议您添加有关您的方案的更多详细信息(router.jsmodels/forummodels/categories文件会有所帮助),以便我可以尝试提供更准确的答案。 Ember版本的细节也可以提供帮助。

与此同时,this discussionthis guide可能会有所帮助。

相关问题