如何在Ember数据中的一个JSON请求中加载两个模型? [英] How do I load two models in one JSON request in Ember-data?
问题描述
使用Ember-data和Ember.js,我试图加载两个具有一个JSON请求的模型。模型有类似的关系:
Using Ember-data and Ember.js, I'm trying to load two models with one JSON request. The models have a relationship analogous to this:
App.Person = DS.Model.extend({
name: DS.attr('string'),
dogs: DS.hasMany('App.Dog'),
});
App.Dog = DS.Model.extend({
name: DS.attr('string'),
owner: DS.belongsTo('App.Person'),
});
我的服务器正在发送JSON:
My server is sending JSON like this:
{
"dog": {
"id": 1,
"name": "Fido",
"owner": {
"id": 1,
"name": "John Smith",
"dogs": [1]
}
}
}
...但是,Ember数据仍然向我的服务器发送请求(使用findQuery),尝试得到所有者的JSON。
…And yet, Ember-data still sends a request (using findQuery) to my server trying to get the owner JSON.
我有一个jsFiddle设置,演示它此处。要观察问题发生,您需要转到此链接才能激活路由/模板:
I have a jsFiddle set up that demonstrates it here. To watch the problem happen, you'll need to go to this link to activate the route/template:
http://fiddle.jshell.net/6kQ8s/2/show/#/dog/1
我没有在我的适配器中定义findQuery(),因为我不需要它来获取我已经发送的数据...对吗?
I haven't defined findQuery() in my adapter on purpose because I shouldn't need that to get data that I have already sent… Right?
有人知道我在这里做错了吗?
Does anyone know what I'm doing wrong here?
推荐答案
我正在做以下(使用ember-data revision 8)
I'm doing the following (using ember-data revision 8)
App.Dog = DS.Model.extend({
name: DS.attr('string'),
owner: DS.belongsTo('App.Person', { embedded: true }),
});
此外,我必须告诉序列化器加载此关系的映射。
虽然不是必需的,我使用我自己的DS.Serializer子类。在初始化
时,序列化程序加载Person类的映射,该类指定应加载
嵌入式关系。
Additionally, I have to tell the serializer to load a mapping for this relation. Though it's not required, I'm using my own DS.Serializer subclass. At initialisation time the serializer loads a mapping for the Person class, which specifies that embedded relationships should be loaded.
App.WOSerializer = DS.Serializer.extend({
init: function(){
this._super();
this.map(App.Dog, {
person: {
embedded: 'load'
}
});
});
由问题提问者编辑:
需要在适配器中初始化序列化程序。
The serializer needed to be initialized in the adapter.
App.adapter = DS.Adapter.create({
// ...
serializer: App.WOSerializer.create()
});
这篇关于如何在Ember数据中的一个JSON请求中加载两个模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!