首页 > 解决方案 > Sencha 存储基于 ids 的多对一关系生成

问题描述

在尝试解决多对一关系时,我似乎无法让 sencha 根据给定的 ID 自动生成它们。

我有两个模型和两个商店(在 4 个文件中):

型号Customer

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

门店客户:

Ext.define('MyApp.store.Customer', {
    extend: 'Ext.data.Store',
    storeId: 'Customer',
    alias: 'store.customer',
    autoLoad: true,

    model: 'Customer',

    data: {
        items: [
            {id: 1, name: 'paul'},
            {id: 3, name: 'W'}
        ]
    },

    proxy: {
        type: 'memory',
        reader: {
            type: 'json',
            rootProperty: 'items'
        }
    }
});

模型票:

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

最后是售票处:

Ext.define('MyApp.store.Ticket', {
    extend: 'Ext.data.Store',
    storeId: 'Ticket',
    alias: 'store.ticket',
    autoLoad: true,

    model: 'Ticket',

    data: {
        items: [{id: 1000, title: 'blah', customerId: 1}]
    },

    proxy: {
        type: 'memory',
        reader: {
            type: 'json',
            rootProperty: 'items'
        }
    }

});

现在这应该相当简单:我有一个“有”单张票的客户。我将这些商店分开而不是在客户商店中定义所有内容的原因是因为稍后我希望分别加载和处理这两个东西。

现在,当我运行它并在某个控制器中测试此设置时,我发现了一个惊人的结果:

const thestore = Ext.data.StoreManager.lookup('Customer');
const ticketstore = Ext.data.StoreManager.lookup('Ticket');
debugger;

const customer = thestore.findRecord('id', 1);
const ticket = ticketstore.findRecord('id', 1000);

const t = customer.tickets();
const c = ticket.getCustomer();
const basename = customer.get('name');
const customername = c.get('name');
console.dir(basename);
console.dir(customername);

我注意到“basename”和“customername”是不相等的,实际上customername 是“空白”:这表明引用根本不起作用。使用调试器确实表明现在有两个不同的模型,id 为“1”,并且工单已经创建了自己的客户(而不是自己与客户挂钩)。

如何定义(在为票店返回数据时)票属于客户?

标签: extjsextjs6many-to-onerelational

解决方案


它应该在您的客户模型中使用 hasmany 配置,类型为 Ticket。

hasMany: [
    {
        name: 'Ticket',
        model: 'Ticket'
    },
]

它会自动将工单与客户相关联,但您必须在客户表中拥有与工单表相关的外键。我希望它会有所帮助。


推荐阅读