-
15 Feb 2012 2:34 PM #1
Unanswered: Need help with hasOne association
Unanswered: Need help with hasOne association
I'm trying to create a hasOne association on a model, and provide the associated data along with the parent model's data.
But I'm not sure how to configure the association, or how to access the associated data from an instance of the parent model. Could someone point me in the right direction?
As an example, with data like this:
And models like this:Code:{ firstName: 'Joe', address: { street: 'Avenue L', city: 'Brooklyn' } }
What would I put inside hasOne? And how would I access a Person's associated Address?Code:Ext.define('app.model.Person', { extend: 'Ext.data.Model', config: { fields: [ {name: "firstName", type: "string"} ], hasOne: { // this is the part I'm not sure about model: 'app.model.Address', name: 'address' }, proxy: { type: 'ajax', ... reader: { type: 'json' } } } }); Ext.define('app.model.Address', { extend: 'Ext.data.Model', config: { fields: [ {name: "street", type: "string"}, {name: "city", type: "string"} ] } });
The intro to the API docs for HasOne is a little confusing. It seems to indicate that if X hasOne Y, the hasOne association should be configured on Y's model, not X's. Is this a typo? Also, the config names on the Ext.data.association.* classes (e.g. "associatedModel") are different from the ones used in almost every example (e.g. "model"). So it's not clear what maps to what.
-
15 Feb 2012 5:05 PM #2
Yes, the documentation for that is wrong and will be updated in the next release. Sorry about that!
Your hasOne association should be on the person. The name field will automatically map to the field ont he record (so 'address' would use the 'address' field and create the 'getAddress' getter). If for some reason you want these to be different, you can use 'associationKey' to set the actual record field to be used.
Is your code working?Sencha Inc.
Robert Dougan - @rdougan
Sencha Touch 2 and Ext JS 4 Core Team Member, SASS/Theming Wizard.
-
15 Feb 2012 5:38 PM #3
It didn't work as posted, although I've managed to cobble together something that works.
- The "name" config doesn't seem to do anything with HasOne. It seems like this only works with HasMany.
- Instead, I replaced it with two separate configs: "associationKey" for the field containing the associated data, and "getterName" for the getter function name:
Code:hasOne: { model: 'app.model.Address', associationKey: 'address', getterName: 'getAddress' } - In addition, I had to specify a proxy on the Address model. This seems strange, since I might want to use this model in other contexts:
Code:proxy: { type: 'memory' }


Reply With Quote