Loading associated data in Sencha Touch without nesting

Viewed 2278

I'm working on a basic Sencha Touch application that displays a list of text messages and the name of an associated user that sent the message. I have followed the tutorials online on how to setup model associations but each tutorial assumes that the server produces data with a nested structure.

The data I am working with has a flat structure with primary/foreign key relationships, and I cannot figure out how to get Sencha to load both stores from a single response.

model/User.js

Ext.define('App.model.User', {
    extend: 'Ext.data.Model',

    config: {
        fields: [
            { name: 'uid', type: 'number' },
            { name: 'name', type: 'string' },
        ]
    }
});

store/Users.js

Ext.define('App.store.Users', { 
    extend: 'Ext.data.Store',                                                    

    config: {                                                                    
        model: 'App.model.User',                                                 
        autoLoad: true,
    }
});

model/Message.js

Ext.define('App.model.Message', {
    extend: 'Ext.data.Model',

    config: {
        fields: [
            { name: 'id', type: 'number' },
            { name: 'uid', type: 'number' },
            { name: 'message', type: 'string' }
        ],

        associations: [{
            type: 'belongsTo',
            model: 'App.model.User',
            primaryKey: 'uid',
            foreignKey: 'uid'
        }],

        proxy: {
            type: 'jsonp',
            url: 'messages.json',

            reader: {
                type: 'json',
                rootProperty: 'req_messages'
            }
        }
    }
});

store/Messages.js

Ext.define('App.store.Messages', {
    extend: 'Ext.data.Store',

    config: {
        model: 'App.model.Message',
        autoLoad: true,
    }
});

The messages are correctly loaded and displayed by my application (sample JSON response below), but I cannot figure out how to get the associated users to be loaded into the store. Can this be solved with a configuration, or will I need a custom reader? Any help appreciated!

Sample JSON

{
    "users": [{
        "uid": "1",
        "name": "John"
    }, {
        "uid": "3033",
        "name": "Noah"
    }],
    "req_messages": [{
        "id": "539",
        "uid": "1",
        "message": "my message"
    }, {
        "id": "538",
        "uid": "1",
        "message": "whoops"
    }, {
        "id": "534",
        "uid": "3033",
        "message": "I love pandas."
    }]
}
1 Answers
Related