【发布时间】:2014-04-30 22:10:52
【问题描述】:
我正在尝试在 Sencha Touch 2.3.1 中创建一个简单的模型关联。
基本上我想要一个按类别排列的优惠券商店。所以每个类别都有很多优惠券。
我的数据目前在商店声明中被硬编码(没有代理或服务器)。
类别模型声明:
Ext.define('Category', {
extend: 'Ext.data.Model',
config: {
idProperty: 'id',
fields: [
{ name: 'id'},
{ name: 'name' },
{ name: 'itemType'}
],
hasMany: [
{
associatedModel: 'Coupon',
name: 'Coupons',
foreignKey: 'category_id'
}
]
}});
优惠券模型:
Ext.define('Coupon', {
extend: 'Ext.data.Model',
config: {
fields: [
{ name: 'couponId'},
{ name: 'title'},
{ name: 'description'},
{ name: 'category_id'},
],
belongsTo: [
{
model: 'Category',
name: 'Category',
associationKey: 'category_id'
}
]
}});
分类存储和数据:
Ext.define('CategoryStore', {
extend: 'Ext.data.Store',
config: {
autoLoad: true,
data: [
{
id: 1,
name: "cat1"
},
{
id: 2,
name: "cat2"
}
],
model: 'Category',
storeId: 'CategoryStore'
}});
优惠券商店:
Ext.define('CouponStore', {
extend: 'Ext.data.Store',
config: {
autoLoad: true,
data: [
{
id: '1',
title: 'coupon1',
description : 'some desc',
category_id:1
},
{
id: '2',
title: 'coupon2',
description : 'desc2',
category_id:2
}
],
model: 'Coupon',
storeId: 'CouponStore'
}
});
最后,app.js 中启动函数中的代码:
Ext.application({
name: 'hasmany',
launch: function () {
// Destroy the #appLoadingIndicator element
Ext.fly('appLoadingIndicator').destroy();
var categoryStore = Ext.create('CategoryStore');
var cat2 = categoryStore.findRecord('name','cat2');
console.log(cat2.getData()); //This works fine
console.log(cat2.Coupons().getData()); //This returns an empty array
}
});
结果: hasMany 关联方法 cat2.Coupons() 返回一个空数组:
Chrome 控制台:
> Object {id: 2, name: "cat2", itemType: undefined} app.js:100
Class {all: Array[0], items: Array[0], keys: Array[0], indices: Object, map: Object…}
任何帮助将不胜感激,谢谢!
* 编辑: 我设法使用一种解决方法达到了预期的结果:
var couponStore = Ext.create('CouponStore');
couponStore.filter('category_id',2);
所以目前这对我来说已经足够了,但是我很想知道为什么我以前的代码不起作用。
【问题讨论】:
标签: sencha-touch has-many model-associations associative