2

i have working example of code with relations, but there is a lack - backbone replaces my foreign id with related model, i would like to keep as foreign id and to add related model with new key.. is it possible?

In the following example engineId will be replaces with related model. Is it possible to keep as engineId as related model with key 'engine'?

window.Car = Backbone.RelationalModel.extend({
  defaults : {
    id     : null,
    brand  : null,
    engineId : null,
  }
});

window.Engine = Backbone.RelationalModel.extend({
  defaults : {
    id : null,
    type : null,
  },
  relations: [{
    type         : 'HasMany',
    key          : 'cars',
    relatedModel : 'Car',
    reverseRelation: {
      key: 'engineId',
    }
  }]
});

var engines = new Backbone.Collection([
  {id : 1, type : 'electric'},
  {id : 2, type : 'diesel'},
], {model: window.Engine});

var cars = new Backbone.Collection([
  {id : 1, brand : 'Toyota', engineId : 2},    
  {id : 2, brand : 'Ford', engineId : 2},    
  {id : 3, brand : 'Tesla', engineId : 1},    
], {model: window.Car});

cars.each(function(car){
  console.log(car.get('id'), car.get('brand'), car.get('engineId').get('type'));
});
avasin
  • 9,186
  • 18
  • 80
  • 127

1 Answers1

0

Is there any reason you can't just get the id from the Engine model? Eg.

car.engine.get('id')
Andru
  • 7,011
  • 3
  • 21
  • 25