Question

Imagine we have two tables in mysql: cars and engines.

Cars table row will have following structue:

  • id: int
  • engineId: int (foreign key to engines.id column)
  • brand: string

Engines table row this one:

  • id: int,
  • type: string (imagine we have electric and diesel engines)

So, i want to retrieve all data from these tables, create model collections on client side and finally display table with merged results:

  • car id
  • brand name
  • engine type

So, i've tried many examples, but i can't get what i am doing wrong. Can you assist please?

// Create car model
window.Car = Backbone.RelationalModel.extend({

});

// Create engine model
window.Engine = Backbone.RelationalModel.extend({
  relations: [{
    type: 'HasMany',
    key: 'cars',
    relatedModel: 'Car',
    reverseRelation: {
      key: 'engine',
      includeInJSON : 'engineId',
    }
  }]
});

// Create engine instance
var engine = new window.Engine({
  id : 1,
  type : 'electric',
});

// Create car instance
var car = new window.Car({
  id       : 1,
  brand    : 'Toyota',
  engineId : 1, 
});

// i expect to get 'electric'
console.log(car.getRelation('engine').type); 
Was it helpful?

Solution

Try this:

// Create car model
var Car = Backbone.RelationalModel.extend({
});

// Create engine model
var Engine = Backbone.RelationalModel.extend({
    relations: [{
        type: 'HasMany',
        key: 'cars',
        relatedModel: Car,
        reverseRelation: {
            key: 'engine'
        }
    }]
});

// Create engine instance
var engine = new Engine({
  id : 1,
  type : 'electric'
});

// Create car instance
var car = new Car({
  id       : 1,
  brand    : 'Toyota',
  engine   : 1
});

// get 'electric'
console.log(car.get('engine').get('type'));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top