Composite models (models within models), or manual foreign key associations between models?

旧城冷巷雨未停 提交于 2020-01-17 07:56:21

问题


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.Lists 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!