2012-05-01 3 views

답변

5

예를 들어 관계가 많은 경우 A 빌딩에는 많은 방이 있습니다.

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"부분을 지정합니다.

+0

룸 모델에서도 관계를 정의해야한다고 생각했지만 자동으로 찾습니다. 그래서'lab.get ('building')'은 science_building을 반환 할 것입니다. 감사합니다 –

+1

이 대답은 결국 저에게 백본 관계형을 갖게했습니다. 고맙습니다! –