如何使用主干和主干关系创建和使用属于(或多对一)的关系?
例如,如果你们的关系是,一栋楼有很多房间。 房间属于建筑物:
Building = Backbone.RelationalModel.extend({
relations: [
{
type: 'HasMany',
key: 'rooms',
relatedModel: 'Room',
reverseRelation: {
key: 'building'
}
}
]
});
Room = Backbone.RelationalModel.extend();
house = new Building({id:1});
science_building = new Building({id:2});
console.log(house.get('rooms').length); // ==> 0
living_room = new Room({building:1,name:"Living Room"});
lab = new Room({building:2,name:"Chemistry Lab"});
console.log(house.get('rooms').length); // ==> 1
console.log(house.get('rooms').first().get('name')); // ==> "Living Room"
console.log(science_building.get('rooms').length); // ==> 1
console.log(science_building.get('rooms').first().get('name')); // ==> "Chemistry Lab"
属性指定关系的"belongs_to"部分。