Search code examples
extjssencha-touchsencha-touch-2

Is it possible to have multiple hasMany relationships using the same model?


I have a situation where I have a model meant to store several lists of chemicals. The chemical model is the same for each of the hasMany relationships.

I need something like this:

Ext.define('HandSurvey.model.ChemicalRisks', {
    extend: 'Ext.data.Model',
    requires: ['Ext.data.identifier.Uuid'],
    config: {
        idProperty: 'id',
        identifier: 'uuid',
        fields: [
            { name: 'id', type: 'auto' }
        ],
        associations: [
            {
                type: 'hasMany',
                model : 'HandSurvey.model.SpecificChemical',
                name  : 'fiberglassResins',
                store : {
                    type: 'sql'
                }
            },
            {
                type: 'hasMany',
                model : 'HandSurvey.model.SpecificChemical',
                name  : 'paintsStains',
                store : {
                    type: 'sql'
                }
            },
        ],
        proxy: {
            type: 'sql'
        }
    }
});

But this would cause each list to bind to every SpecificChemical that belongs to the ChemicalRisks model, not just the ones meant to belong to that hasMany. It seems as though I would need to join on multiple fields

Is it possible to do this? Or do I have to make a bunch of the exact same models/stores with different names?


Solution

  • sure you can!

    use associationKey and the autogenerated stores of the associations

    associations: [
                {
                    type: 'hasMany',
                    model : 'HandSurvey.model.SpecificChemical',
                    name  : 'fiberglassResins',
                    associationKey : 'fiberglassResins'
                },
                {
                    type: 'hasMany',
                    model : 'HandSurvey.model.SpecificChemical',
                    name  : 'paintsStains',
                    associationKey : 'paintsStains'
                },
            ]
    

    Given a response like this: {

        "response" : {
            "fiberglassResins": [
                {
                    "id"   : 1
                    "name" : "Polyester"
    
                },
                {
                    "id"   : 2
                    "name" : "E-Glass"
                }
    
            ],
            "paintsStains": [
                {
                    "id"   : 1
                    "name" : "item1"
    
                },
                {
                    "id"   : 2
                    "name" : "item2"
                }
    
            ]
        }
    }
    

    Then you bind your main model to a store lets say ItemsStore. IMPORTANT each record of ItemsStore will get autogenerated by Sencha: fiberglassResinsStore and paintsStainsStore.

    Yo can console.log() each record to see the actual stores.