介绍
我在使用ExtJS的Ext.data.Model
类时遇到了一个应用程序设计问题。我将尝试在这里开发一个非常常见的在线商店场景,以便您可以跟随我的思路。我真的很感谢任何关于我的想法和结论的评论!
模型
假设您想要将“每个客户都可以订购多个产品”映射到ExtJS中。从这些单词中可以确定涉及以下三个模型:Customer
、Order
和Product
。在这种情况下,Order
是连接Customer
和Product
的东西。
关联
我发现ExtJS实际上允许您使用Ext.data.HasManyAssociation
和Ext.data.BelongsToAssociation
类来指定此(Customer)1-n(Order)1-n(Product)
关系。但这是人们想要的吗?您是否希望Product
始终属于Order
?如果您想要没有与Order
有任何连接的Product
列表呢?
存储
这就是它变得更加ExtJS特定的地方。在ExtJS中,您有Ext.data.Store
来保存所有数据。对我来说,组织我的数据的一种自然方式是为每个模型都有一个Ext.data.Store
:
CustomerStore
OrderStore
ProductStore
考虑将三个Ext.grid.Panel
并排放置;每个存储一个。在第一个网格中选择客户时,在第二个网格中自动显示他的订单。在第二个网格中选择订单时,相关产品会出现在第三个网格中。
这听起来自然吗?如果不是,请发表评论!
将所有内容汇总
现在我们有三件需要汇总的事情:
- 模型及其
- 关联(
hasMany
、belongsTo
)和 - 数据(
Store
)
是否可能仅从一个模型-模型关系的一侧定义关联?例如,我可以指定一个Order
hasMany
Product
,但省略Product
belongsTo
Order
吗?因为一个Product
实际上可以属于多个Order
。因此,我在下面指定了Product
模型hasMany
Order
。
客户
Ext.define('Customer', {
extend : 'Ext.data.Model',
requires : [
'Order',
],
fields : [
{name : 'id', type : 'int'},
{name : 'lastname', type : 'string'}
{name : 'firstname', type : 'string'}
],
hasMany: 'Order' /* Generates a orders() method on every Customer instance */
});
订单
Ext.define('Order', {
extend : 'Ext.data.Model',
fields : [
{name : 'id', type : 'int'},
{name : 'customer_id', type : 'int'}, /* refers to the customer that this order belongs to*/
{name : 'date', type : 'date'}
],
belongsTo: 'Customer', /* Generates a getCustomer method on every Order instance */
hasMany: 'Product' /* Generates a products() method on every Order instance */
});
产品
Ext.define('Product', {
extend : 'Ext.data.Model',
fields : [
{name : 'id', type : 'int'},
{name : 'name', type : 'string'},
{name : 'description', type : 'string'},
{name : 'price', type : 'float'}
],
/*
I don't specify the relation to the "Order" model here
because it simply doesn't belong here.
Will it still work?
*/
hasMany: 'Order'
});
以下是商店列表:
客户店铺
Ext.define('CustomerStore', {
extend : 'Ext.data.Store',
storeId : 'CustomerStore',
model : 'Customer',
proxy : {
type : 'ajax',
url : 'data/customers.json',
reader : {
type : 'json',
root : 'items',
totalProperty : 'total'
}
}
});
订单存储
Ext.define('OrderStore', {
extend : 'Ext.data.Store',
storeId : 'OrderStore',
model : 'Order',
proxy : {
type : 'ajax',
url : 'data/orders.json',
reader : {
type : 'json',
root : 'items',
totalProperty : 'total'
}
}
});
产品商店
Ext.define('ProductStore', {
extend : 'Ext.data.Store',
storeId : 'ProductStore',
model : 'Product',
proxy : {
type : 'ajax',
url : 'data/products.json',
reader : {
type : 'json',
root : 'items',
totalProperty : 'total'
}
}
});
这里有一个与公司和其产品相关的示例(不是我写的)http://superdit.com/2011/05/23/extjs-load-grid-from-another-grid/。它使用了两个模型和两个存储,但没有定义任何关联。
提前感谢您。
-Konrad