骨干关系属于

时间:2012-05-01 14:29:34

标签: backbone.js backbone-relational

如何使用骨干和骨干关系创建和使用属于(或多对一)关系?

1 个答案:

答案 0 :(得分:5)

如果您的关系是,例如,A Building有很多房间。房间属于建筑物:

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"

reverseRelation属性指定关系的“belongs_to”部分。