4

The example from docs about many-to-many relationship supposes that companies would be added after the person was already created.

However, what if the person data comes from server with a list of companies (companies' ids) already?

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

// 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 the same way I'd do with one-to-many relations, 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's the fiddle you can play with: http://jsfiddle.net/ymr5Z/

Georgii Ivankin
  • 2,702
  • 2
  • 23
  • 35

1 Answers1

0

Your MAIN problem is that you are trying to add Jobs by ID. You never created any job object though let alone set their id! You only created the companies.

A better way to go about adding jobs is to have an addJob() function which you give a company ID (or company) and it creates the Job model for you.

Full Code to fit your example

and specifically:

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 perfectly. You might also want to set an includeInJSON to false for your reverse relationship on 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]
    }
}]
Toli
  • 5,547
  • 8
  • 36
  • 56