我有两个模型:Book belongsTo Author。让我们调查一下作者数据与书籍数据一起从服务器到 ExtJs 并返回的过程。服务器向 ExtJs 发送以下嵌套数据:
{
success : true,
data: {
id: '23',
name: 'JavaScript - The definitive guide'
author: { // <<-- nested author data
id: '45',
name: 'David Flanagan',
}
}
}
在 ExtJs 方面,数据由以下模型处理:
Ext.define('My.models.Book', {
extend: 'Ext.data.Model',
idProperty: 'id',
fields: [
'id',,
'name',
{name: 'author_id', mapping: 'Author.id'}, // <<-- flat author data
],
proxy: {
type: 'ajax',
api: {
read: 'My/Books/index',
create: 'My/Books/create',
update: 'My/Books/update',
destroy: 'My/Books/delete'
},
reader: {
type: 'json',
root: 'data',
},
writer: {
type: 'json',
root: 'data',
},
},
associatinons: [{
type: 'belongsTo',
model: 'My.models.Author',
associationKey: 'Author',
}]
});
由于模型( )字段上的Author.id
映射,我能够将作者的数据加载到旨在编辑书籍数据的以下表单:author_id
Book
{name: 'author_id', mapping: 'Author.id'}
Ext.define('My.views.books.Form', {
extend: 'Ext.form.Panel',
initComponent: function () {
var me = this;
me.items = [{
xtype: 'container',
layout:'anchor',
defaults:{
anchor: '95%'
},
items:[{
xtype: 'textfield',
fieldLabel: 'Book title',
name: 'name'
},{
xtype: 'combo',
fieldLabel: 'Author',
name: 'author_id', // <<-- flat author data
store: ...
}]
}];
me.buttons = [{
text: 'Save',
scope: me,
handler: me.onSave
}];
me.callParent(arguments);
},
...
});
当然有一个专用于作者的模型,但是当我需要一次将书籍和作者数据加载到一个表单中时,我(暂时)看不到上面显示的其他可能性(当然请给我看,如果有更好的解决方案)。
现在问题来了:我将从组合中选择其他作者并保存表单。随着书籍记录变脏(author_id
现在显示为Book
模型字段),将提出对'My/Books/update'
URL 的请求(这很好,我正在编辑书籍),并将以下数据发送到服务器:
{
data: {
id: '23',
name: 'JavaScript - The definitive guide',
author_id: '78' // <<-- flat author data
}
}
返回服务器的数据与发送到 ExtJs 的结构不同,必须进行某种翻译,例如:
$data['Author']['id'] = @$data['author_id'];
unset($data['author_id']);
我在问:是否可以通过 ExtJs 形式处理数据,使它们以与来自服务器相同的结构返回服务器?如何?
这个问题已经在这里、这里和这里以某种方式讨论过,但这些讨论都没有明确回答。
提前感谢您的帮助!:)