PDA

View Full Version : Nested Json and belongs to



John Sourcer
9 Mar 2013, 1:59 PM
I've spent a long time looking at this and can't seem to get it right:

With this JSON:


[{"LocationId":1,"LocationName":"New York","Prizes":[{"PrizeId":1,"PrizeQuantity":1,"WonPrizes":0},{"PrizeId":2,"PrizeQuantity":20,"WonPrizes":1}]}]

I'm trying to populate the following store for a grid:


Ext.define('PrizesModel', {
extend: 'Ext.data.Model',
fields: [
{ name: 'pots', mapping: 'Prizes[0].PrizeQuantity' },
{ name: 'potsWon', mapping: 'Prizes[0].WonPrizes' }
],
belongsTo: 'LocationModel'
});

Ext.define('LocationModel', {
extend: 'Ext.data.Model',
fields: [
{ name: 'LocationName', type: 'string' }
],
hasMany: [{ model: 'PrizesModel', name: 'prizes', }]
});

var store = Ext.create('Ext.data.Store', {
autoDestroy: true,
model: 'LocationModel',
proxy: {
type: 'ajax',
url: 'prizes.json',
reader: {
type: 'json'
}
}
});

But as soon as I add the association the grid blanks. I'd appreciate any pointers.

mitchellsimoens
11 Mar 2013, 7:19 AM
Try with these models:


Ext.define('PrizesModel', {
extend : 'Ext.data.Model',

fields : [
{ name : 'pots', mapping : 'PrizeQuantity' },
{ name : 'potsWon', mapping : 'WonPrizes' }
]
});

Ext.define('LocationModel', {
extend : 'Ext.data.Model',

idProperty : 'LocationId',
fields : [
'LocationName'
],
hasMany : [
{ model : 'PrizesModel', name : 'prizes', associationKey : 'Prizes' }
]
});

Couple things I did. I associationKey to properly allow the association to find the right property in the JSON. Also fixed the mapping configs in the PrizesModel. Added idProperty in the LocationModel.

Last thing I did was removed the belongsTo association in the PrizesModel. The reason I did that was it looked like it was incomplete and when the hasMany association creates the child store with the Prizes data, each record in that child store will automatically get the belongsTo association back to the location record it was a hasMany of.

Try these models and let me know what it does.