我有两个相关的模型:
//models/school.js
import DS from 'ember-data';
import { belongsTo } from 'ember-data/relationships';
import { hasMany } from 'ember-data/relationships';
export default DS.Model.extend({
name: DS.attr('string'),
zipCode: DS.attr('string'),
kids: hasMany('kid',{inverse: 'schoolId',async:true}),
district: belongsTo('district',{inverse:'schools',async:true}),
grades: hasMany('grade',{inverse: 'schools'}),
});
//models/district.js
import DS from 'ember-data';
import { hasMany } from 'ember-data/relationships';
export default DS.Model.extend({
name: DS.attr('string'),
zipCode: DS.attr('string'),
schools: hasMany('school',{inverse: 'district',async:true}),
});
Accordind到文档https://guides.emberjs.com/v2.2.0/models/relationships/#toc_relationships-as-promises,当我试图通过学校到达学区时,有时学区会返回null,就像学校与任何学区没有关系一样,但所有学校都与学区有关。我不明白这一点。
//routes/kid-info.js
import Ember from 'ember';
export default Ember.Route.extend({
setupController(controller,model){ //the model is kid
this._super(controller,model);
controller.set('districts',this.store.findAll('district'));
controller.set('schools',this.store.findAll('school'));
controller.set('grades',this.store.findAll('grade'));
var schoolId=model.get('schoolId.id');
controller.set('selectedSchool',model.get('schoolId'));
let school=this.store.peekRecord('school',schoolId);
if(school){
school.get('district').then((district)=>{
controller.set('selectedDistrict',district); //the district is sometimes null
});
}
},
更新
根据@Thernys的建议,我改变了这样的路线:
import Ember from 'ember';
export default Ember.Route.extend({
setupController(controller,model){
this._super(controller,model);
controller.set('districts',this.store.peekAll('district'));
controller.set('schools',this.store.peekAll('school'));
controller.set('grades',this.store.peekAll('grade'));
controller.set('selectedSchool',model.get('schoolId'));
model.get('schoolId.district').then(function(district) {
controller.set('selectedDistrict',district);
});
},
但我仍然有相同的结果。就像学校与学区没有正确关系一样。 JIC我在设置控制器呼叫之前加载了学校和学区。
答案 0 :(得分:0)
这最终解决了我的问题:
model.get('schoolId').then(function(school) {
controller.set('selectedDistrict',that.store.peekRecord('district',school.get('district_id')));
});