EmberJS自动加载反向关系?

时间:2014-09-24 16:28:45

标签: ember.js

我有一个类似的模型:

var Survey = DS.Model.extend({
  title: DS.attr('string'),
});

var SurveySection = DS.Model.extend({
  survey: DS.belongsTo('survey', {async:true}),
  title: DS.attr('string'),
  help_text: DS.attr('string'),
});

如果我有一个调查对象,我可以survey.get('survey_section')来获取与特定调查相关的所有部分,因为这不起作用吗?如果我在调查模型中添加survey_sections: DS.hasMany('survey_sections', {async:true}),它甚至无法正常工作。

我应该补充一点,我正在使用灯具。当我发布应用程序时,他们仍然会被使用(即如果RESTAdapater会修复它,那在我的情况下不是解决方案):

Survey.reopenClass({
  FIXTURES: [
  {
    "id": 1, 
    "title": "Favourite food"
  }, 
  {
    "id": 2, 
    "title": "Sports"
  }
]
});

SurveySection.reopenClass({
  FIXTURES: [
  {
    "help_text": "", 
    "id": 1, 
    "survey": 1, 
    "title": "Italian food"
  }, 
  {
    "help_text": "", 
    "id": 2, 
    "survey": 1, 
    "title": "Team sports"
  }, ...]});

灯具适配器是否无法像这样反方向检索相关记录?如果没有,我是否必须采用费力的方式手动获取survey=1的部分(例如,因为我不得不在整个应用程序中使用其他模型采用这种方法)?

更新

具体来说,我的失败代码是(调查1):

this.get('survey').get('survey_sections').then(function(survey_sections) {
  // survey_sections contains no objects, so objectAt(0) returns undefined.
  survey_sections.objectAt(0).get('questions').then(function(questions) {
    console.log('Set first question ID to ' + self.get('firstQuestionId'));
  });
});

由于灯具显示在survey_sections中应该有2个SurveySection对象,但是没有找到。

1 个答案:

答案 0 :(得分:0)

我不想这样做,但我必须在Survey fixture中添加前向关系,例如:

Survey.reopenClass({
  FIXTURES: [
  {
    "id": 1, 
    "title": "Favourite food",
    "survey_sections": [1, 2],
  }, 
  {
    "id": 2, 
    "title": "Sports",
    "survey_sections": [3],
  }
]
});

并使用以下内容更新Survey模型

survey_sections: DS.hasMany('survey_sections', {async:true})