zrz*_*zrz 6 orm relationship bookshelf.js
我将Bookshelf模型定义为
var Country =  Bookshelf.Model.extend({
    tableName: 'countries',
});
var Address =  Bookshelf.Model.extend({
    tableName: 'addresses',
    country: function() {
        return this.belongsTo(Country,'country_id');
    },
});
Run Code Online (Sandbox Code Playgroud)
现在我可以从数据库中获取我的一个模型
new Country({name:"Italy"}).fetch()
.then(function(country){
Run Code Online (Sandbox Code Playgroud)
并创建和地址
    new Address({...}).save().then(function(address){
Run Code Online (Sandbox Code Playgroud)
但是我在文档中找不到哪种方法可以帮助我建立'belongsTo'关系.无需手动将country_id属性设置为正确的属性.
我唯一看到构建关系的是collection.create(object)方法(http://bookshelfjs.org/#Collection-create),它被描述为方便从对象创建模型,保存它,以及将它添加到集合中; 我不知道怎么做最后一部分.
无论如何,当collectionName引用hasOne或belongsTo关系时,collection.create似乎不适用于model.related('collectionName'),因为它们不会重新发送集合.
按照你的方式,你需要手动完成它.你应该使用这样的反向关系:
var Country =  Bookshelf.Model.extend({
    tableName: 'countries',
    addresses: function() {
       return this.hasMany(Address);
    }
});
var Address =  Bookshelf.Model.extend({
    tableName: 'addresses',
    country: function() {
        return this.belongsTo(Country,'country_id');
    },
});
Run Code Online (Sandbox Code Playgroud)
然后你应该能够做到:
new Country({name: Italy}).fetch().then(function(italy) {
   // also could be italy.related('addresses'), that would add
   // the addresses collection to the "italy" model's "relations" hash
   return italy.addresses().create({...});
}).then(function(address) {
   // ... saved to the db with the correct address
});
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           8172 次  |  
        
|   最近记录:  |