2012-07-26 54 views
4

example from docs about many-to-many relationship假設公司將在人員創建後添加。如何使用Backbone Relational從初始JSON自動創建多對多關係?

但是,如果個人數據已經來自服務器和公司列表(公司的ID),那該怎麼辦?

是否可以修改這個例子,下面的代碼(或類似的SMT)將是可能的:

// somewhere before we have a collection of companies defined like this: 
// [{id: 1, name: 'ibm'}, {id: 2, name: 'apple'}] 
// and than we do: 
paul = new Person({ 
    name: 'Paul', 
    jobs: [1, 2] 
}) 
paul.get('jobs').at(0).get('name') // 'ibm' 

當試圖做到這一點以同樣的方式我有一個待辦事項許多關係,我失敗:

Companies = Backbone.Collection.extend({model: Company}) 
companies = new Companies([{id: 1, name: 'ibm'}, {id: 2, name: 'apple'}]) 

john = new Person({ 
    name: 'John', 
    jobs: [1] 
}) 

john.get('jobs').toJSON() // [] 
companies.get(1).get('employees').toJSON() // [] 

這裏你可以拉小提琴:http://jsfiddle.net/ymr5Z/

回答

0

你的主要問題是,您要添加Jobs由ID。你從來沒有創造任何工作對象,但更不用說設置他們的ID!你只創建了這些公司。

有關添加作業的更好方法是使用您提供公司ID(或公司)的addJob()函數,併爲您創建Job模型。完美

var Person = Backbone.RelationalModel.extend({ 
    relations: [{ 
     type: 'HasMany', 
     key: 'jobs', 
     relatedModel: Job, 
     reverseRelation: { 
      key: 'person' 
      //includeInJSON: false //if you don't want to show person 
     } 
    }], 
    addJob: function (company) { 
     this.get('jobs').add(new Job({ 
      company: company 
     })); 
    } 
}); 

paul.addJob(1); 
paul.addJob(2); 

作品:

Full Code,以適應您的例子

和具體。您可能還想在作業中將includeInJSON設置爲false,以排除該人的逆向關係!

[{ 
    "company": { 
     "id": 1, 
     "name": "ibm", 
     "employees": [null] 
    }, 
    "person": { 
     "name": "Paul", 
     "jobs": [null, { 
      "company": { 
       "id": 2, 
       "name": "apple", 
       "employees": [null] 
      } 
     }] 
    } 
}, { 
    "company": { 
     "id": 2, 
     "name": "apple", 
     "employees": [null] 
    }, 
    "person": { 
     "name": "Paul", 
     "jobs": [{ 
      "company": { 
       "id": 1, 
       "name": "ibm", 
       "employees": [null] 
      } 
     }, 
     null] 
    } 
}] 
相關問題