问题
I have two models, and I want to "nest" one within the other. Is there a way to do this with Sencha Touch? My models look like this:
Ext.regModel('OuterModel', {
fields: ['name']
});
var outerStore = new Ext.data.Store({
model: 'OuterModel',
data: [
{name: 'item1'},
{name: 'item2'}
]
});
Ext.regModel('InnerModel', {
fields: ['a', 'b']
});
var innerStore = new Ext.data.Store({
model: 'InnerModel',
data: [
{a: 1, b: 5},
{a: 2, b: 5},
{a: 3, b: 3}
]
});
Each OuterModel
needs an associated InnerModel
, and I would love to just be able to have a field that was an inner-model that I could create Ext.List
s from. I could add outerName
to InnerModel
and query on outerName
, but this feels sloppy, manually managing the association.
Is the manual solution my only option, or can I make a model a field of another model?
回答1:
Models can have associations with other Models via belongsTo and hasMany associations. For example, let's say we're writing a blog administration application which deals with Users, Posts and Comments. We can express the relationships between these models like this:
Ext.regModel('Post', {
fields: ['id', 'user_id'],
belongsTo: 'User',
hasMany : {model: 'Comment', name: 'comments'}
});
Ext.regModel('Comment', {
fields: ['id', 'user_id', 'post_id'],
belongsTo: 'Post'
});
Ext.regModel('User', {
fields: ['id'],
hasMany: [
'Post',
{model: 'Comment', name: 'comments'}
]
});
See the docs for Ext.data.BelongsToAssociation and Ext.data.HasManyAssociation for details on the usage and configuration of associations. Note that associations can also be specified like this:
Ext.regModel('User', {
fields: ['id'],
associations: [
{type: 'hasMany', model: 'Post', name: 'posts'},
{type: 'hasMany', model: 'Comment', name: 'comments'}
]
});
来源:https://stackoverflow.com/questions/7604878/composite-models-models-within-models-or-manual-foreign-key-associations-betw