mercredi 30 avril 2014

Creating hasMany associations in Sencha Touch 2

I'm trying to create a simple model association in Sencha Touch 2.3.1.

Basically I want to have a store of coupons, arranged in categories. So every category hasMany coupons.

My data is currently hardcoded in the store declarations (no proxy or server).



Category model declaration :



Code:



Ext.define('Category', {
extend: 'Ext.data.Model',
requires:['Ext.data.Model'],
config: {
idProperty: 'id',
fields: [
{ name: 'id'},
{ name: 'name' },
{ name: 'itemType'}
],
hasMany: [
{
associatedModel: 'Coupon',
name: 'Coupons',
foreignKey: 'category_id'
}
]
}
});



Coupon model :



Code:



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'
}
]
}
});



Category store and data:



Code:



Ext.define('CategoryStore', {
extend: 'Ext.data.Store',


config: {
autoLoad: true,


data: [
{
id: 1,
name: "cat1"
},
{
id: 2,
name: "cat2"
}
],
model: 'Category',
storeId: 'CategoryStore'
}
});



Coupon Store :


Code:



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'
}
});




And finally, the code in the launch function in app.js :


Code:



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
}
});




The Results : The hasMany association method cat2.Coupons() returns an empty array :


Chrome console :


Code:



> Object {id: 2, name: "cat2", itemType: undefined} app.js:100
Class {all: Array[0], items: Array[0], keys: Array[0], indices: Object, map: Object…}

Any help would be appreciated, thanks !



***
EDIT : I managed to achieve the desired results using a manual filter:



Code:



var couponStore = Ext.create('CouponStore');
couponStore.filter('category_id',2);

So that's good enough for me at the moment, however I would be very interested to know why my previous code didn't work.



Aucun commentaire:

Enregistrer un commentaire