2011-08-17 64 views
2

我在網上到處查看了一些東西,但我似乎無法找到在Est Js 4模型中實現多對多關聯的方法。以原型爲例。我有一個「帖子」和「標籤」的應用程序。我如何在Ext Js 4模型中表示這一點,並通過標籤和帖子過濾標籤?在Ext中實現ManyToMany關聯Js 4

+1

我真的不建議你試着用它們的關聯組件來做到這一點,許多人建議你有一個額外的數據存儲到商店之間的關係。我建議你創建自己的商店posts2tags,關聯2個商店,並自己處理過濾器。如果您現在使用它們的關聯組件,您可能已經看到它在每個記錄內部創建了一個存儲。使用它們的關聯組件只會導致您複製數據。 – nscrob

回答

4

ManyToMany意味着有一些額外的表(或數組)包含A和B之間的鏈接。因此,實現這一點的唯一方法是使用額外的存儲。

在有很多的項目,每個人都可以屬於多個類別的情況下,這裏的模型定義:

Ext.define('BS.model.Item', { 
    extend: 'Ext.data.Model', 
    fields: [ 
     {name: 'name'     , type: 'string'}, 
    ], 

    proxy: { 
     type: 'direct', 

     api: { 
      create: Items.Create, 
      read: Items.GetTree, 
      update: Items.Update, 
      destroy: Items.Delete, 
     }, 
    }, 

    hasMany: {model: 'BS.model.ItemInCategory', name: 'categories', foreignKey: 'itemId'}, 
}); 

Ext.define('BS.model.ItemCategory', { 
    extend: 'Ext.data.Model', 
    fields: [ 
     {name: 'name'  , type: 'string'}, 
    ], 

    proxy: { 
     type: 'direct', 

     api: { 
      create: ItemCategories.Create, 
      read: ItemCategories.Read, 
      update: ItemCategories.Update, 
      destroy: ItemCategories.Delete, 
     }, 
    }, 

}); 

Ext.define('BS.model.ItemInCategory', { 
    extend: 'Ext.data.Model', 
    fields: ['itemId', 'categoryId'], 

    // This will allow create operations with multiple records 
    clientIdProperty: 'clientId', 

    proxy: { 
     type: 'direct', 

     api: { 
      create: ItemInCategory.Create, 
      read: ItemInCategory.Read, 
      destroy: ItemInCategory.Destroy, 
     }, 

     reader: { 
      type: 'json', 
      root: 'data', 
     },   
    }, 

}); 

然後讓所有類別的項目屬於:

Item.categories().load({ 
    scope: this, 
    callback: function(aRecords, aOperation, aSuccess) { 

     Ext.each(aRecords, function(aAssociation) { 
      // Do something here 
     }, this); 

    }     
}); 

然後添加關聯:

var iNewRecord = Item.categories().model.create({ categoryId: '16' }); 

Item.categories().add(iNewRecord); 
+0

這是一個很好的解決方案。我會給出熟悉的答案。 – acteon

0

對於ExtJS的6,ManyToMany實現了。

最小實現:

Ext.define('App.models.Group', { 
extend: 'Ext.data.Model', 

manyToMany: [ 
    'User' 
] 

});