EXTJS4自学手册——EXT数据结构组件(Model之间的关系)

来源:互联网 发布:下载贵金属分析软件 编辑:程序博客网 时间:2024/06/06 04:17

在现实情况中,模型与模型之间常常有1对多,多对多关系,这种关系可以被EXT的数据组件支持。

在EXT中,这种关系有2中类型:

1.belongsTo:当前模型与指定模型之间的关系是多对一

2.hasMany:当前模型与指定模型之间的关系是一对多

例子:

我们定义3个Model(作者、书籍、章节),一个作者有写了许多书籍,一本书有许多章节

作者的数据结构如下

复制代码
    <script type="text/javascript">
Ext.onReady(
function () {
//定义作者的数据结构
Ext.define('Author', {
extend:
'Ext.data.Model',
fields: [
//包含一个字段id,数据类型是int型
{name: 'id', type: 'int' },
//包含一个字段name,数据类型是string型
{name: 'name', type: 'string' },
],
//一个作者包含多本书,通过书籍的authorId字段关联
hasMany: { model: 'Book', foreignKey: 'authorId' },
proxy: {
//从 'http://www.cnblogs.com/Scripts/myInformation.js'加载数据
url: 'http://www.cnblogs.com/Scripts/myInformation.js',
type:
'rest'
}
});

});
</script>
复制代码



 

 

书籍的数据结构如下:

复制代码
    <script type="text/javascript">
Ext.onReady(
function () {
//定义书籍的数据结构
Ext.define('Book', {
extend:
'Ext.data.Model',
fields: [
//包含id字段,类型int
{name: 'id', type: 'int' },
//包含title字段,类型string
{name: 'title', type: 'string' },
//包含pages字段,类型int
{name: 'pages', type: 'int' },
//包含numChapters字段,类型int
{name: 'numChapters', type: 'int' },
//包含authorId字段,类型int,和author书籍的id字段关联
{ name: 'authorId', type: 'int' }
],
//一本书包含多个章节,通过章节的bookId字段关联
hasMany: { model: 'Chapter', foreignKey: 'bookId' }
});

});
</script>
复制代码

章节的数据结构如下:

复制代码
    <script type="text/javascript">
Ext.onReady(
function () {
//定义章节的数据结构
Ext.define('Chapter', {
extend:
'Ext.data.Model',
fields: [
//包含id字段,类型int
{name: 'id', type: 'int' },
//包含number字段,类型int
{name: 'number', type: 'int' },
//包含title字段,类型string
{name: 'title', type: 'string' },
//包含bookId字段,类型int,和book数据的id字段关联
{ name: 'bookId', type: 'int' }
]
});
});
</script>
复制代码

创建json数据:

复制代码
{
"authors": [
{
"id": 1,
"name": 'Shea Frederick',
"books": [ {
"id": 11,
"title": 'Learning Ext JS 3.2',
"pages": 432,
"numChapters": 17,
"chapters": [
{
"id": 111,
"number": 1,
"title": 'Getting Started'
},
{
"id": 112,
"number": 2,
"title": 'The Staples of Ext JS'
}
]
},
{
"id": 12,
"title": 'Learning Ext JS',
"pages": 324,
"numChapters": 14,
"chapters": [
{
"id": 123,
"number": 3,
"title": 'Forms'
},
{
"id": 124,
"number": 4,
"title": 'Buttons, Menus, and Toolbars'
}
]
}
]
}
]
}
复制代码

加载作者信息:

复制代码
            Author.load(1, {
success: function () {
alert("加载成功")
}
}
)
复制代码

执行结果:

 

展示ID为1的作者有哪些书

复制代码
 Author.load(1, {
success: function (author) {
//获取作者有哪些书
var books = author.books();
//遍历书籍
books.each(function (book) {
console.log("书籍名称:" + book.get('title'));
})
}
}
)
复制代码

执行结果:

展示ID为1的作者的第一本书有多少章节及哪些章节:

复制代码
 Author.load(1, {
success: function (author) {
//获取作者有哪些书
var books = author.books();
//或者作者的第一本书有哪些章节
var chapters = books.getAt(0).chapters();
//输出章节数
console.log("共" + chapters.getCount() + "章,章节明细如下:");
//遍历章节,输出章节名称
chapters.each(function (chapter) {
console.log(chapter.get('title'));
})
}
}
)
复制代码

执行结果:

 

 

注:除了使用hasMany属性可以连接Model外,还可以使用belongTo实现同样的效果,使用方式和hasMany一样,不过方向相反,详见EXTJS文档

原创粉丝点击