【发布时间】:2011-10-01 03:51:26
【问题描述】:
简介
我在 ExtJS 中遇到了 Ext.data.Model 类的应用程序设计问题。我将在这里尝试将我的想法发展为一个非常常见的在线商店场景,因此您可以关注我。我真的很感激任何关于我的想法和结论的cmets!
型号
假设您想将“每个客户都可以订购多种产品”这一事实映射到 ExtJS。一言以蔽之,可以识别出这三个模型:Customer、Order 和Product。在这种情况下,Order 是连接 Customers 和
Products.
协会
我发现 ExtJS 实际上允许您使用 Ext.data.HasManyAssociation 和 Ext.data.BelongsToAssociation 类指定此 (Customer)1-n(Order)1-n(Product) 关系。但这就是人们想要的吗?您是否希望Product 始终属于Order?如果您想要一个Products 列表而与Orders 没有任何联系怎么办?
商店
这是它获得更多 ExtJS 特定的地方。在 ExtJS 中,您有 Ext.data.Stores 来保存您的所有数据。对我来说,组织数据的一种自然方式是为我的每个模型设置一个 Ext.data.Store:
CustomerStoreOrderStoreProductStore
考虑将三个Ext.grid.Panels 并排放置;每个商店一个。在一个网格中选择客户时,他的订单会自动显示在第二个网格中。在第二个网格中选择订单时,相关产品会出现在第三个网格中。
这听起来自然吗?如果没有,请发表评论!
把所有东西放在一起
所以现在我们需要把三件事放在一起:
- 模型及其
- 协会(
hasMany、belongsTo)和 - 数据 (
Stores)
是否可以仅从模型-模型关系的一侧定义关联?例如,我可以指定 Order hasMany Products 但忽略 Product belongsTo 和 Order 吗?因为Product 实际上可以属于多个Order。因此我在下面指定Product模型hasManyOrders。
ExtJS 中的模型如下:
客户
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/ 的示例(不是我做的)。它使用两个模型和两个商店,但没有定义关联。
提前谢谢你
-康拉德
【问题讨论】:
-
您不需要指定关联,我个人不需要。
标签: extjs data-modeling store model-associations