一旦模型定义,如何建立bookshelf.js关系?

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'),因为它们不会重新发送集合.

tgr*_*ser 7

按照你的方式,你需要手动完成它.你应该使用这样的反向关系:

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)

  • 您似乎只能在`belongsToMany`关系上使用`attach`.我不相信你能做到`italy.addresses().attach(...)`.据我所知,你必须通过自己设置ID来手动建立这种关系,如果你没有在创建时这样做,尽管这方面的文档有点缺乏.这里有一个相关的[bug](https://github.com/tgriesser/bookshelf/issues/71) (2认同)