Wednesday, December 25, 2013

How to use hasMany association in Sencha Touch Model

Hello,

In this blog I will explain how to use "hasMany" associations in Sencha Touch models. First lets see what are the associations in Sencha Touch.  Normally in RDBMS we have primary key and foreign keys and using which we can reference data from other tables. For example students and course. Here one course can have many students and a student belongs to specific course. This types of associations we can have in Sencha Touch. Sencha Touch data package supports associations along the models. For this blog lets take an example of Products and Merchants. Here a merchant can have many products and a product belongs to a marchant. In this case your models definition would look like following.

Ext.define('MyApp.model.Merchant', {
    extend: 'Ext.data.Model',

    config: {
        fields: [
            { name: 'id',                   type: "int"},
            { name: 'name',                 type: "string"}
        ],
        associations: [{ type: 'hasMany', associatedModel: 'MyApp.model. Product', name: 'products' }]
    }

});

Ext.define('MyApp.model.Product', {
    extend: 'Ext.data.Model',

    config: {
        fields: [
            { name: 'id',                   type: "int"},
            { name: 'title',                type: "string"},
            { name: 'description',          type: "string"},
            { name: 'cost',           type: "float"}
        ],
        idProperty: 'id',
        associations: [{ type: 'belongsTo', model: 'MyApp.model.Merchant', name: 'merchant' }]
    }

});

Above is the definition of product and merchant models. Here we have used associations config to define it. Merchant has specified the association as hasMany and product model specified it with belongsTo . You can specify more then one associations on single model. If you see the definition of association, we have specified three config here, type, model and name. Type is the type of association, associateModel specifies the other model and name defines the key of field.  You can use getter and setter with this name or use this name in list or dataview tpl. Please note here you have to specify both hasMany and belongsTo association to each model .If you skip either, it will not work.  Now let's say we have to set tpl in the list for the products and show the merchant name there. You tpl should like like this.

var goodTpl = new Ext.XTemplate(
    '<div>',
        '<div>{title}</div>',
         '<div class="goodmerchant">By {merchant.name}</div>',
    '</div>'
);

As you see above we have used merchant.name to display name of the merchant for the product. It will fetch merchant name from merchant store using the association.

No comments:

Post a Comment