Search code examples
extjsmany-to-oneauto-generateextjs6-modern

Sencha keyed many to one relation, with complex (namespace) name


The official documentation on sencha has a simple example of a many-to-one relationship. It uses "reference" field to identify the relationship.

A slightly modified example is below, this works:

Ext.define('Customer', {
    extend: 'Ext.data.Model',
    fields: ['id', 'name']
});

Ext.define('Ticket', {
    extend: 'Ext.data.Model',
    fields: ['id', 'title', {
        name: 'customerId',
        reference: 'Customer'
    }]
});
const customer = new Customer({id: '1', name: 'paul'});
const ticket = new Ticket({id: '1000', title: 'blah', customerId: '1'});
const t = customer.tickets();
const c = ticket.getCustomer();
console.dir(t);
console.dir(c);

Now I tried to modify this further, by renaming the "Customer" class to use a namespace (as per conventionion in sencha):

Ext.define('Long.Name.Customer', {
    extend: 'Ext.data.Model',
    fields: ['id', 'name']
});

Ext.define('Ticket', {
    extend: 'Ext.data.Model',
    fields: ['id', 'title', {
        name: 'customerId',
        reference: 'Long.Name.Customer'
    }]
});
const customer = new Long.Name.Customer({id: '1', name: 'paul'});
const ticket = new Ticket({id: '1000', title: 'blah', customerId: '1'});
const t = customer.tickets();
const c = ticket.getCustomer();

However now suddenly the classes aren't generated anymore and there is an array that customers.tickets isn't defined (and ticket.getCustomer is also not defined).

How do I use namespaces with many-to-one relations?

And furthermore: what are the rules for the generated method? -- I notice Customer.tickets() uses plural (adds -s to the function name): what would happen on a word that ends on 's'? Are there "rules" for these generated methods?


Solution

  • For the use of namespace I found a solution, the getterName property of the reference field helps. Together with the complementory inverse. The definition for the Ticket class would then become:

    Ext.define('Ticket', {
        extend: 'Ext.data.Model',
        fields: ['id', 'title', {
            name: 'customerId',
            reference: {
                type: 'Look.Out.Customer',
                inverse: 'tickets',
                getterName: 'getCustomer',
                setterName: 'setCustomer',
            }
        }]
    });
    

    While I was unable to find information regarding the automated naming (other than "it's based on the role and mostly add -s"), being able to manually name the generated methods sidesteps the issue.