骨干关系一对一关系,如何获取父模型数据?

时间:2016-03-04 09:20:45

标签: backbone.js backbone-relational

exampleData = {
    id: 1,
    name: 'A',
    house: {
        address1: 'California'
        address2: 'California'
    }
}

House = Backbone.RelationalModel.extend({
    urlRoot: function urlRoot() {
        var personId = this.get('person').id; // this.get('person') is null

    }
});


Person = Backbone.RelationalModel.extend({
    relations: [
        { // Create a (recursive) one-to-one relationship
            type: Backbone.HasOne,
            key: 'house',
            relatedModel: House,
            reverseRelation: {
                type: Backbone.HasOne,
                key: 'person'
            }
        }
    ],

    initialize: function() {
    }
});

我需要在House模型中获取此人的模型数据,

但是this.get(' person')返回null,即使我设置了reverseRelation。

如何在内部获取个人资料?

1 个答案:

答案 0 :(得分:0)

我认为你的代码不起作用。模型的定义有点不对。定义关系时,它应该是对象的引用,而不是字符串值:

relatedModel: House // instead of 'House' as a string

然后你可以通过吸气剂从每个模型中引用,类似:

houseModel.get("person");
personModel.get("house");