PDA

View Full Version : How to structure relational store data?



omphe
15 Dec 2010, 7:24 AM
Trying to figure out the Sencha way of dealing with relational data.

If you have a number of models that relate in arbitrary ways, should you load data into your Sencha application with all of the data nested, or should you create a number of separate stores and extract data from them using related keys?

Nested data:


{
fruits:[
{ fruit: 'apple', color: 'red'},
{ fruit: 'strawberry', color: 'red'},
{ fruit: 'orange', color: 'orange'},
],
tShirts:[
{ type: 'metallica', color: 'black'},
{ type: 'man-united', color: 'red'},
]
}


or Flat relational data


{
fruits:[
{ fruit: 'apple', color_id: 1'},
{ fruit: 'strawberry', color_id: '1},
{ fruit: 'orange', color_id: 2},
],
tShirts:[
{ type: 'metallica', color_id: 3},
{ type: 'man-united', color_id: '1},
],
colors:[
{ color: 'red', id: 1},
{ color: 'orange', id: 2},
{ color: 'black', id: 3},
]
}



I'm inclined to have a single store in my application with all the data nested and repeating, but this seems really wasteful. Having looked into the Association classes, its not clear how the foreignKey or association properties work.

What's the common approach to stores? Many specialised or single multi-purpose?

edspencer
15 Dec 2010, 2:56 PM
Typically there will be many specialized Stores. In your example you might have something like this:



Ext.regModel('Fruit', {
fields: ['id', 'fruit', 'color_id'],

belongsTo: 'Color'
});

Ext.regModel('TShirt', {
fields: ['id', 'type', 'color_id'],

belongsTo: 'Color'
});

Ext.regModel('Color', {
fields: ['id', 'color']
});


You can then load your flat relational data (your second code paste) into a Store and traverse it like this:



new Ext.data.Store({
model: 'Fruit',
proxy: {
type: 'ajax',
url : '/path/to/your/json',
reader: {
type: 'json',
root: 'fruits'
}
},

autoLoad: {
callback: function(records) {
var apple = records[0];

//should log the red color
console.log(apple.getColor());
}
}
});