PDA

View Full Version : How to get model associations working?



RoyalSens
26 Oct 2013, 1:22 AM
I've created a simple test project in Sencha Architect 2.2.3 and used ExtJS 4.2.2 for testing model associations. But it seems that it does not work as I expect it...

I created two stores and their models: Persons and Addresses with some test data.


Ext.define('MyApp.store.Persons', {
extend: 'Ext.data.Store',


requires: [
'MyApp.model.Persons'
],


constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
model: 'MyApp.model.Persons',
storeId: 'Persons',
data: [
{
id: 1,
name: 'test1',
address_id: 1
},
{
id: 2,
name: 'test2',
address_id: 2
},
{
id: 3,
name: 'test3',
address_id: 3
}
],
proxy: {
type: 'ajax',
reader: {
type: 'json'
}
}
}, cfg)]);
}
});
Ext.define('MyApp.store.Addresses', {
extend: 'Ext.data.Store',


requires: [
'MyApp.model.Addresses'
],


constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
model: 'MyApp.model.Addresses',
storeId: 'Addresses',
data: [
{
address_id: 1,
name: 'address1'
},
{
address_id: 2,
name: 'address2'
},
{
address_id: 3,
name: 'address3'
}
],
proxy: {
type: 'ajax',
reader: {
type: 'json'
}
},
fields: [
{
name: 'id'
},
{
name: 'name'
}
]
}, cfg)]);
}
});

Ext.define('MyApp.model.Persons', {
extend: 'Ext.data.Model',


uses: [
'MyApp.model.Addresses'
],


fields: [
{
name: 'id'
},
{
name: 'name'
},
{
name: 'address_id'
}
],


hasOne: {
associationKey: 'address_id',
model: 'MyApp.model.Addresses',
primaryKey: 'address_id',
foreignKey: 'id'
}
});

Ext.define('MyApp.model.Persons', {
extend: 'Ext.data.Model',


uses: [
'MyApp.model.Addresses'
],


fields: [
{
name: 'id'
},
{
name: 'name'
},
{
name: 'address_id'
}
],


hasOne: {
associationKey: 'address_id',
model: 'MyApp.model.Addresses',
primaryKey: 'address_id',
foreignKey: 'id'
}
});




In the Addresses model, I created a 'hasOne' associations. However, when I get a record from the Persons store and try to get the associated data with r.getAsocciatedData(), I get an empty object. What did I do wrong? I already tried to change some settings on the hasOne association, but I don't get it working.

I have added the Test project to demonstrate the complete app:46574

mitchellsimoens
28 Oct 2013, 12:53 PM
Associations don't know about external stores meaning you have 2 stores in the code you provide and you want to hook them together but that's not how the associations work. They work off a single remote data source.

RoyalSens
29 Oct 2013, 3:52 AM
It's too bad that it doesn't work with multiple stores, but thank you for the answer.
Maybe the documentation should be updated to make this clear from the start?!