我整个晚上都在试图解决这个问题,但没有成功。我有一个 JSON 结构如下(来自另一个系统,所以我无法更改其结构):
{
"parents":{
"parent":[
{
"parentId":1,
"children":{
"child":[
{
"childId":1,
},
{
"childId":2,
}
]
}
},
{
"parentId":2,
"children":{
"child":[
{
"childId":1,
},
{
"childId":2,
}
]
}
}
],
"pageNum":1,
"pageSize":2
}
}
但是,我无法弄清楚数据模型的正确结构应该是什么。我已经尝试过以下方法,但它不起作用。顺便说一句,我可以访问家长信息。问题在于访问儿童信息。所以,我猜我设置关系数据的方式有问题。
Ext.regModel("ParentModel", {
hasMany: {
model: 'ChildrenModel',
name: 'children.child' // not too sure about this bit
},
fields: [
{name: 'parentId', type: 'string'}
],
proxy: {
type: 'ajax',
url : 'models.json',
reader: {
type: 'json',
root: 'parents.parent' // this works fine
}
}
});
Ext.regModel('ChildrenModel', {
belongsTo: 'ParentModel', // not too sure about this bit
fields: [{name: 'childId', type: 'string'}]
});
使用数据存储:
Ext.regStore('ParentModelStore', {
model: 'ParentModel',
autoLoad:true
});
我使用以下模板获取父信息,但无法从中获取子数据:
myapp.views.ParentView = Ext.extend(Ext.Panel, {
layout: 'card',
initComponent: function() {
this.list = new Ext.List({
itemTpl: new Ext.XTemplate(
'<tpl for=".">',
'<div>',
'{parentId}', // this works fine
'</div>',
'<tpl for="children.child">', // this doesn't work
{childId}
'</tpl>',
'</tpl>',
),
store: 'ParentStore',
});
this.listpanel = new Ext.Panel({
layout: 'fit',
items: this.list,
});
this.items = this.listpanel;
myapp.views.ParentView.superclass.initComponent.apply(this, arguments);
},
});
Ext.reg('ParentView', myapp.views.ParentView);
我所困扰的是“子”和“父”元素分别被另一个元素“子”和“父”包围。
非常感谢任何帮助。
提前致谢,
Philip
PS 如果我删除外部“children”包装元素并只保留内部“child”元素(并将模型定义中的“children.child”更改为“child”),则代码可以正常工作。
PPS 我正在回答我自己的问题:
哎哟!我忘记将“children”元素添加到 ParentModel 的字段中。
它应该如下所示(注意:我不需要指定“hasMany”或“associations”元素 - 不太确定为什么会这样或包含它们的好处是什么):
Ext.regModel("ParentModel", {
fields: [
{name: 'parentId', type: 'string'},
{name: 'children'} // VERY IMPORTANT TO ADD THIS FIELD
],
proxy: {
type: 'ajax',
url : 'models.json',
reader: {
type: 'json',
root: 'parents.parent' // this works fine
}
}
});
Ext.regModel('ChildrenModel', {
fields: [{name: 'childId', type: 'string'}]
});
该模板也可以正常工作:
'<tpl for="children.child">', // this syntax works too.
{childId}
'</tpl>',