How to automatically create many-to-many relationships from initial JSON with Backbone Relational?

An example from many-to-many relationships documents suggests that companies will be added after the person has already been created.

However, what if a person’s data comes from a server with a list of companies (company identifiers) already?

Is it possible to modify the example so that the following code (or smt.) Can be used:

// 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' 

When trying to achieve this in the same way as with a one-to-many relationship, I fail:

 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() // [] 

Here you can play with: http://jsfiddle.net/ymr5Z/

+4
source share
1 answer

Your main problem is that you are trying to add Jobs by ID. You never created a task object, although not to mention setting your identifier! You have created only companies.

The best way to add tasks is the addJob() function, which you give to the company (or company) identifier, and it creates the Job model for you.

Full code as per your example

and in particular:

 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); 

Works great. You might also want to set includeInJSON to false for your inverse relationship to the job, to exclude the person!

 [{ "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] } }] 
0
source

All Articles