View Full Version : Models: Nested structures vs assocations/hasOne etc?

21 Jun 2012, 4:04 AM
I am just curious if there is a better way of doing this than using mappings. E.g. I could have a the following JSON structure loaded via REST from some web backend:

var itemsData = [ { Id: 'a', Name: 'Box 1', Dim: { Width: 100, Height: 50 } },
{ Id: 'b', Name: 'Box 2', Dim: { Width: 300, Height: 600 } }

In this case I could write a model definition like this:

extend: 'Ext.data.Model',
fields: [
{ name: 'Height', mapping: 'Dim.Height', type: 'int' },
{ name: 'Width', mapping: 'Dim.Width', type: 'int' }
idProperty: 'Id'

However, even if this may work in this example, it could be that at times I have some items WITH a dimension, and others without, e.g. the following type of data:

var itemsData = [
{ Id: 'a', Name: 'Box 1', Dim: { Width: 100, Height: 50 } },
{ Id: 'b', Name: 'Box 2' }

In my case it's not a case of dimension data, but other types of optional "an object that may have one nested object structure", the dimension case is just an example.

In this case the nested object / complex type does not get loaded from somewhere else, so it is not a foreign key type of relation and neither has an Id of its own: it's just a sub structure.

I played around with using a "hasOne" association, and separating the Dim as a separate type, and then adding it as the assocation. However, I have no idea how I'm supposed to optionally set that item then, as if I do
anItem.set("Dim", Ext.Create("Dim", { Width: 100, Height: 200 })) it ends up being set as the string "[Object object]".

For a "hasMany" association I read that you get a proxy store, like ".dims()" that you can then ".add()" to etc. How does this work with "hasOne"? The documentation says there will be a "setXXX()" method being created, but I don't get one unless I manually specify its name as a "setterName", but even then, calling it doesn't set anything anywhere. I'm confused :-/

(Sure, I can do anItem.data.Dim = Ext.Create("Dim", ..}).Data or something equally breakneck, but that obviously is not very smart.)

How am I supposed to model/solve these kind of structures?
Can it be done automatically through the modelling (e.g. hasOne), or would I really have to write a data structure converter or mapping?!

6 Sep 2012, 2:41 PM
Is there no one out there can give me a hint with this? I'm back at this problem here once again, and I'm a few hours away from just saying "screw it" and doing something code-wise ugly that I'll regret sooner or later :s