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

标签 orm relationship bookshelf.js

我将书架模型定义为

var Country =  Bookshelf.Model.extend({
    tableName: 'countries',
});

var Address =  Bookshelf.Model.extend({
    tableName: 'addresses',
    country: function() {
        return this.belongsTo(Country,'country_id');
    },
});

现在我可以从数据库中获取我的模型之一
new Country({name:"Italy"}).fetch()
.then(function(country){

并创建和地址
    new Address({...}).save().then(function(address){

但是我在文档中找不到什么方法可以帮助我建立 'belongsTo' 关系。无需手动将 country_id 属性设置为正确的属性。

我看到建立关系的唯一方法是 collection.create(object) 方法( http://bookshelfjs.org/#Collection-create ),它被描述为从对象创建模型、保存模型并将其添加到集合中的便利;我也不知道怎么做最后一部分。

无论如何, collection.create 似乎不适用于 model.related('collectionName') 当 collectionName 指的是 hasOne 或belongsTo 关系时,因为它们不代表集合。

最佳答案

按照你的方式,你需要手动完成。你应该使用这样的逆关系:

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');
    },
});

那么你应该能够做到:
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

});

关于orm - 一旦模型定义,如何建立 bookshelf.js 关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21559954/

相关文章:

grails - Grails 1:m获得最多的关系

javascript - Node.js/Bookshelf - 表中的多个列引用另一个表的 ID 的映射模型

database - ORM自动建表违反DBA偏好

python - Sqlalchemy 与内置类型的关系

php - 从相关模型 laravel 获取 id

javascript - Bookshelf.js与json属性中的外键的关系

express - knex.js - 仅调试 SQL

orm - Big O 与 N+1 有什么关系?

php - Propel - 检索所有表

php - Django 中的 ORM 与 PHP Doctrine