2013-08-07 72 views
2

我有代碼與關係的工作示例,但缺乏 - 主幹用相關模型替換我的外部標識,我想保留爲外部標識並添加與新鑰匙相關的模型..有可能嗎?骨幹關係,在模型中使用關係時保留外鍵id

在以下示例中,engineId將替換爲相關模型。是否有可能將engineId保留爲具有關鍵「引擎」的相關模型?

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')); 
}); 
+0

對此問題的任何解決方案? –

回答

0

是否有任何理由不能從引擎模型中獲取id?例如。

car.engine.get('id')