Bookshelf.js嵌套withRelated()(相当于多个内连接)

时间:2018-05-27 11:52:26

标签: bookshelf.js

我是使用Bookshelf的新手,并试图找出如何进行多个连接的等效操作。我想这与withRelated有关,不知何故?我知道我可以用彼此的结果做几个查询,但这看起来很糟糕。

具体来说,我有几个表:用户,组织,端点和设置。

我希望,在给定用户名的情况下,返回包含所有列的端点列表及其关联设置及其所有列以及相关组织的名称。

使用Bookshelf有一个很好的方法吗?我看到这个用于此类用例的Bookshelf EZ Fetch plugin,但想知道 “原生”语法,就像它一样。

以下是我的模特:

用户:

'use strict';

const bookshelf = require('../config/bookshelf_instance');
const Promise = require('bluebird');
const bcrypt = Promise.promisifyAll(require('bcrypt'));
const Role = require('./role');
const securityConfig = require('../config/security_config');
const Organization = require('./organization');

module.exports = bookshelf.Model.extend({
    tableName: 'user',
    roles() {
        return this.belongsToMany(Role, 'map_user_role');
    },
    validPassword(password) {
        return bcrypt.compareAsync(password, this.attributes.password);
    },
    organization(){
        return this.hasOne(Organization, 'organization_id');
    },
    initialize() {
        this.on('saving', model => {
            if (!model.hasChanged('password')) return;

            return Promise.coroutine(function* () {
                const salt = yield bcrypt.genSaltAsync(securityConfig.saltRounds);
                const hashedPassword = yield bcrypt.hashAsync(model.attributes.password, salt);
                model.set('password', hashedPassword);
            })();
        });
    }
});

组织:

'use strict';

const bookshelf = require('../config/bookshelf_instance');
const Endpoint = require('./endpoint');
const User = require('./user');
const Group = require('./endpoint_group');

module.exports = bookshelf.Model.extend({
    tableName: 'organization',
    endpoints() {
        return this.hasMany(Endpoint, 'organization_id');
    },
    users() {
        return this.hasMany(User, 'organization_id');
    },
    groups() {
        return this.hasMany(Group, 'organization_id');
    }
});

端点:

'use strict';

const bookshelf = require('../config/bookshelf_instance');
const ezFetch = require('bookshelf-ez-fetch');
const Organization = require('./organization');
const Settings = require('./endpoint_settings');
const Group = require('./endpoint_group');

bookshelf.plugin(ezFetch());

module.exports = bookshelf.Model.extend({
    tableName: 'endpoint',
    organization() {
        return this.hasOne(Organization, 'organization_id');
    },
    settings() {
        return this.hasOne(Settings, 'settingsId')
    },
    group() {
        return this.belongsToMany(Group, 'parentGroupIds')
    }
});

环境:

'use strict';

const bookshelf = require('../config/bookshelf_instance');
const Endpoint = require('./endpoint');

module.exports = bookshelf.Model.extend({
    tableName: 'endpoint_setting',
    endpoint() {
        return this.hasOne(Endpoint, 'endpoint_settings_id')
    }
});

1 个答案:

答案 0 :(得分:0)

如果有其他人遇到这个问题,一位同事告诉我,ORM通常不擅长此类事情。我最后只是做了一系列查询。