S
S
styv2014-04-29 22:34:50
ExtJS/Sencha
styv, 2014-04-29 22:34:50

ExtJS New model, save and hasMany connection

Good afternoon.
There was a problem with models and relationships. There is a pattern like this:

Ext.define('App.model.Server', {
    extend: 'Ext.data.Model',
    
    fields: [...],

    hasMany: [
       {
            name: 'ports',
            model: 'App.model.Port',
            foreignKey: 'server_id',
            associationKey: 'ports'
       }
    ]
});

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

    fields: [
        'server_id',
        ...
    ]
});

So the problem is that I need to create a new server model and add ports to it (to a model that has not yet been saved) and send it all to the backend. I decided to save in two stages, first the server model, then the ports.
But the whole problem is that after saving the server model, the backend gives the saved ID for the model, but this ID is not assigned for nested port models, i.e. server_id is left empty.
Can someone tell me where to dig? ))
So far there are two options: either go through the store and fill in the server ID or rewrite the writer and try to send ports along with the server in one request, I don’t know how convenient it will be when editing / deleting ports.
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
styv, 2014-05-31
@styv

There was no time to answer my own question, but here is the solution that was applied:
https://gist.github.com/yuristrelets/9b543be8cd8af... Let me
explain a little:
The “original” method code was copied into copyFrom, although callParent could have been called , but then you would have to repeat all the checks again.
The updateHasManyAssociations method code is quite simple, it takes a single argument - the id of the new model.
Here we go through all the associations of the model, but we “react” only to the hasMany type. Next, we update the field with the foreign key (stored in the foreignKey variable) for all records of the related store. This is necessary for records that are already in the store.
In order for the foreign key to be set automatically for records that will be added later, we look for the modelDefaults property of the store and update the property with the name of the foreign key in it. The modelDefaults object stores all the default values ​​for the added models and is used in the insert method of the store.
Well, the last step is to update the filter value for the associated store, this may come in handy for its further reload.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question