假设我们在mysql中有两个表:cars和engines。
汽车表行将具有以下结构:
id
:intengineId
:int(engines.id
列的外键)brand
:字符串
发动机表行这一行:
- CCD_ 5:int
type
:string(假设我们有电动和柴油发动机)
所以,我想从这些表中检索所有数据,在客户端创建模型集合,并最终显示具有合并结果的表:
- 汽车id
- 品牌名称
- 发动机类型
所以,我试过很多例子,但我不明白我做错了什么。你能帮忙吗?
// 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);
试试这个:
// 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'));