EXTJS有很多模型,父模型没有来自子模型的任何数据

时间:2014-12-07 03:21:21

标签: extjs model-view-controller model

我正在尝试使用hasmany关联来嵌套嵌套模型。如何将任何数据添加到父模型?我将数据添加到子模型中,并期望在JSON中的父模型下看到它,如下所示 - >

    "ChildModel": [{
       "field1": "11",
       "field2": "12",

    }, {
       "field1": "13",
       "field2": "14",
    }]


    Ext.define('ParentModel', {
       extend: 'Ext.data.Model',
       requires: [
           'ChildModel'
       ],
       proxy: {
           type: 'rest',
           batchActions: true,
           url: 'test/saveModel',
           reader: {
               type: 'json',
               root: 'childModel'
           }
       },
       hasMany: [{
           model: 'ChildModel',
           name: 'ChildModel'
       }]
    });

    Ext.define('ChildModel', {
       extend: 'Ext.data.Model',
       fields: [{
           name: 'field1'
       }, {
           name: 'field2'
       }]
    });

    #
    Controller code
    parent = Ext.create('ParentModel');
    child = parent.ChildModel();
    Ext.each(selectedProducts, function(item) {
       child.add({
           field1: item.data.f1,
           fi2ld2: item.data.f2
       });
    });

    console.info(child); //has all the records selected in the grid
    console.info(parent); // has no records

1 个答案:

答案 0 :(得分:1)

这是我的工作代码示例:

AbstractModel:

Ext.define('Sender.model.AbstractModel', {
extend: 'Ext.data.Model',
identifier: 'negative'
, schema: {
    namespace: 'Sender.model'
}});

两个模型继承自AbstractModel:

工作模式(父母)......

Ext.define('Sender.model.Job', {
extend: 'Sender.model.AbstractModel',
fields: [
    {
        name: 'date'
    }
]
, validators: [
    {type: 'presence', field: 'date'}
]});

...和队列模型(儿童)

Ext.define('Sender.model.Queue', {
extend: 'Sender.model.AbstractModel',
fields: [
    {
        name: 'people_id'
        , type: 'int'
    }
    , {
        name: 'message_id'
        , type: 'int'
    }
    , {
        name: 'jobId'
       , reference: 'Job'
    }
]});

在控制器中使用:

    var job = new Sender.model.Job();
    job.set('date', new Date())
    var queues = job.queues();
    for (var i = 0; peoples.length > i; i++) {
        for (var j = 0; messages.length > j; j++) {
            var queue = new Sender.model.Queue();
            queue.set('people_id', peoples[i].getId());
            queue.set('message_id', messages[j].getId());
            queues.add(queue);
        }
    }
    queues.save();
以这种方式,job.queues()你可以接触孩子

JSON生成取决于代理的类型,在这种情况下:

Request URL:http://sender/Queue?_dc=1418054245301
Request Method:POST
Content-Type:application/json 
Request  Payload:    
[{"id":-193,"people_id":14,"message_id":18,"jobId":-2},"id":-194,"people_id":14,"message_id":17,"jobId":-2}]