Pages

Friday, May 25, 2012

Rules for HasOne and BelongsTo Associations in ExtJS

  1. Put the proxy in the model, unless you have a very good reason not to [1]
  2. Always use fully qualified model name
  3. Always set the getterName
  4. Always set the setterName
  5. Always set the associationKey, if the foreign object is returned in the same response as this object
  6. Always set the foreignKey, if you want to load the foreign object at will
  7. Consider changing the instanceName to something shorter
  8. The getter behaves differently depending on whether the foreign object is loaded or not. If it's loaded, the foreign object is returned. Otherwise, you need to pass in a callback to get it.
  9. You should set the name property if you plan to override this association.
  10. You do not need a belongsTo relationship for a hasMany to work
  11. Set the primaryKey property if the id field of the parent model is not "id"
  12. Sometimes you need to use uses or requires for the belongsTo association. Watch out for circular references though.
  13. Calling setter() function does not seem to set the instance. Set object.belongsToInstance = obj  if calling the setter().

Ext.define('Assoc.model.PhoneNumber', {
    extend:'Ext.data.Model',

    fields:[
        'number',
        'contact_id'
    ],

    belongsTo:[
    {
      name:'contact',
      instanceName:'contact',
      model:'Assoc.model.Contact',
      getterName:'getContact',
      setterName:'setContact',
      associationKey:'contacts',
      foreignKey:'contact_id'
    }
    ],

    proxy:{
        type:'ajax',
        url:'assoc/data/phone-numbers.json',
        reader:{
            type:'json',
             root:'phoneNumbers'
        }
    }
});

/*
 * Assuming Contact model uses an AJAX proxy with url 'contacts', and its id field is "id", 
 * the below function call will make an http request like this:
 * /contacts?id=88
 */

var pn = new Assoc.model.PhoneNumber( { contact_id:88 } );

pn.getContact( function(contact, operation){ 
  console.log('tried to load contact. this.contact is now set to the contact');
} );

/* you can call phoneNumber.setContact(contact). This will set contact_id on the phone number, BUT it won't set the contact instance on phonenumber, which is likely a bug: */

var contact = new Assoc.model.Contact({id:77});

var phoneNumber = new Assoc.model.PhoneNumber();

phoneNumber.setContact(contact);

console.log(phoneNumber.get('contact_id')) //77

console.log(phoneNumber.contact) //undefined

phoneNumber.contact = contact; //you need to do this if you want to use that reference in the future.






[1] The store will inherit its model's proxy, and you can always override it if necessary

8 comments:

  1. Great stuff. Question - using MVC, would you still keep proxy in model or move to store? is there a difference in whether you have multiple data sources? i.e. store x = data1.json, storey = data2.json?

    ReplyDelete
  2. I like the proxy in the model best. The store will inherit the model's proxy, and you can always override it in the store if you need to.

    I am not a big fan of store sharing. I would make one store instance on demand, unless you have a need to share the store.

    ReplyDelete
  3. Item 10 "You do not need a belongsTo relationship for a hasMany to work".

    I gather you mean "... for a hasOne" to work?

    This, and the hasMany rules, are very helpful. Thanks

    ReplyDelete
  4. Thank you for great tips, and I would like to compliment your rules list based on my experience.

    If your have multiple BelongsTo associations that are using the same model, ExtJS (up to 4.1.1a) will return data only from first associations, because its instance name (used to retrieve the data) is based on: instanceName: associatedName + 'BelongsToInstance'

    To fix this problem, simple solution is to set also "instanceName" with unique value for each assosiation

    ReplyDelete
  5. Cool! This was exactly what I needed to understand how to manipulate the linked hasOne record.

    Thanks a bunch for this example.

    Greg--

    ReplyDelete
  6. Thanks - helped a lot. I would like to save other people from my dumb error. Make sure your store is an 'Ext.data.Store' NOT an 'Ext.data.ArrayStore' - it will replace your json reader with and array reader and cause hard to fathom confusion.

    ReplyDelete
  7. Why the associationKey is set to 'contacts' in BelongTo association for HasOne? Can you post the json or xml of only one contact with phoneNumber in it?

    ReplyDelete
  8. I'd also like to see the JSON related to this set of models.

    ReplyDelete