11

我是Backbone-relational的新手,我不確定什麼是使用HasMany的正確方法。骨幹關係hasmany最佳實踐

我有一個Parent模型有很多children(「很多」,我的意思是成千上萬的孩子)。爲了避免性能問題,我通過外鍵查詢兒童:/child/?parent=1,而不是在Parent中創建child_ids的巨大列表。但似乎這不是主幹關係工作的方式。

所以我想知道什麼是正確的方式來處理這個問題。

1,改變我的JSON API包括在父子ID的列表,然後發送成千上萬的ID爲骨架的關係建議:

url = function(models) { 
    return '/child/' + (models ? 'set/' + _.pluck(models, 'id').join(';') + '/' : ''); 
} 
// this will end up with a really long url: /child/set/1;2;3;4;...;9998;9999 

2,覆蓋許多方法在骨幹關係,讓它處理這個情況。我的第一個想法是:

relations: [{ 
    collectionOptions: function(model){ 
    // I am not sure if I should use `this` to access my relation object 
    var relation = this; 
    return { 
     model: relation.relatedModel, 
     url: function(){ 
     return relation.relatedModel.urlRoot + '?' + relation.collectionKey + '=' + model.id; 
     } 
    } 
    } 
}] 
// This seems work, but it can not be inherent by other model 
// And in this case parent will have am empty children list at beginning.  
// So parent.fetchRelated() won't fetch anything, I need call this url my self. 

3,只使用Backbone-relational作爲Store,然後使用Collection來管理關係。

4,其他一些神奇的方式或模式或骨幹框架

感謝您的幫助。

+1

在我的經驗與骨幹關係,我不認爲它會表現良好的成千上萬的模型。我已經在數百個模型中遇到了一些重要的性能問題 - 特別是在加載它們時。骨幹關係與射擊事件相當「健談」,並且取決於模型中有多少屬性,最終會導致每個模型發射數十個事件並釋放數千個模型。 – 2013-07-02 21:23:04

+0

我很好奇你是如何處理這個問題的。 – 2013-08-05 19:22:14

+0

這是我最終使用的方式,不是很乾淨,但工作到目前爲止。 – xzhang 2013-08-07 02:26:33

回答

1

下面是我對當前項目進行的解決方案。請注意0​​有許多評論,事件,文件和視頻。這些關係及其相反關係在這些模型中定義:

Entities.Project = Backbone.RelationalModel.extend({ 
    updateRelation: function(relation) { 
     var id = this.get('id'), 
      collection = this.get(relation); 

     return collection.fetch({ data: $.param({ project_id: id }) }); 
    } 
}); 

我將REST端點配置爲採用充當連續「WHERE」子句的參數。因此project.updateRelation('comments')將發送請求到/comments?project_id=4我在服務器端有一些進一步的邏輯來過濾掉用戶無權看到的東西。 (Laravel後端,順便說一句)