Extjs hasone association

2019-07-02 01:34发布

问题:

I have Person model, it contains id, first_name, last_name etc and merital_id field. I also have Merital model contains only 2 field: id and title. Server responses JSON like:

{
    success: true,
    items: [
        {
            "id":"17",
            "last_name":"Smith",
            "first_name":"John",
            ...
            "marital_id":1,
            "marital": {
                "id":1,
                "title":"Female"
            }
        },
        ...
    ]
}

So how can I connect my models with association? I still can use record.raw.merital.title in my column.renderer, but I cannot use such fields in templates like {last_name} {first_name} ({merital.title}). What king of association do I need to use, I tryed belongsTo, but when I try to use record.getMarital() I get an error "no such method on record".

I use extjs 4

回答1:

You should be using ExtJS Models, and Associations, in particular the HasOne association.

Documentation:

http://docs.sencha.com/ext-js/4-1/#!/api/Ext.data.association.HasOne

Example:

http://jsfiddle.net/el_chief/yrTVn/2/

Ext.define('Person', {
    extend: 'Ext.data.Model',
    fields: [
        'id',
        'first_name',
        'last_name'
        ],

    hasOne: [
        {
        name: 'marital',
        model: 'Marital',
        associationKey: 'marital' // <- this is the same as what is in the JSON response
        }
    ],

    proxy: {
        type: 'ajax',
        url: 'whatever',
        reader: {
            type: 'json',
            root: 'items' // <- same as in the JSON response
        }
    }
});