很长一段时间以来,我一直在努力理解如何使用 hasMany 和 belongsTo。我的理解是 hasMany 是一个 1:many 关系,belongsTo 是一个many:1 关系——除此之外:这是否意味着如果你有一个 hasMany 关系,它的子模型中需要一个 belongsTo ?我已经阅读了几篇关于它的文章:
- 在Ext.data.reader.Reader页面上加载嵌套数据。
- Ext.data.association.BelongsTo
- Ext.data.association.HasMany
- extjs 4.2 中的关联示例:
- ExtJS 教程 - HasMany 文章
- ExtJS 教程 - BelongsTo 文章
- hasMany vs 属于To
- ExtJS 4:具有关联和存储的模型
不过还是有点糊涂。假设我有以下数据:
var data = {
"config": {
"name": "blah",
"id": 1,
"someconfig": [{
"name": "Services", "tabs": [{
"id": 0, "name": "Details", "layout": "hbox"
}, {
"id": 1, "name": "Sources", "layout": "hbox"
}, {
"id": 2, "name": "Paths", "layout": "hbox"
}, {
"id": 3, "name": "Ports", "layout": "hbox"
}, {
"id": 4, "name": "Levels", "layout": "hbox"
}, {
"id": 5, "name": "Notes", "layout": "hbox"
}]
}, {
"name": "Services2", "tabs": [{}]
}]
}
};
我会为配置创建一个模型:
Ext.define('Config', {
extend: 'Ext.data.Model',
fields: ['name'],
hasMany: [{
name: 'someconfig',
model: 'Someconfig',
associationKey: 'someconfig'
}],
proxy: {
type: 'memory',
data: data,
reader: {
type: 'json',
root: 'config'
}
}
});
所以 Config 可以有很多 Someconfig,因为在数据中,someconfig 是一个对象数组。这是 Someconfig 模型:
Ext.define('Someconfig', {
extend: 'Ext.data.Model',
fields: [
'name'
],
hasMany: [{
name: 'tabs',
model: 'Tabs',
associationKey: 'tabs'
}]
});
好的,同样的交易。Someconfig 可以有很多选项卡,因为在数据中,选项卡是一个对象数组。这是 Tabs 模型:
Ext.define('Tabs', {
extend: 'Ext.data.Model',
fields: [
'id',
'name',
'layout'
],
belongsTo: [{
name: 'tabs',
model: 'Someconfig',
associationKey: 'tabs'
}]
});
现在,belongsTo 在那里,因为我在搞乱这个属性。无论如何,我无法从 Someconfig 访问 Tabs,但我可以从 Config 访问 Someconfig。看看这段代码:
Config.load(1, {
success: function(record, operation) {
console.log(record.get('name')); // works
console.log(record.someconfig().getCount()); // works, gives me 2
console.log(record.someconfig().data.items[0].data); // only prints out name and config_id
// console.log(record.someconfig().tabs()); // doesn't exist
}
});
jsFiddle:演示
我想知道的是,我不应该能够从someconfig()访问tabs( ) ,还是我误解了这些关系?如果是前者,我将如何修复我的代码?
从Sencha 论坛交叉发布。