以多对多关联形式返回模型数据及其相关数据

时间:2017-10-02 15:32:45

标签: knex.js bookshelf.js

我有以下表格:

tasklists: id (PK)
users: id (PK)
tasklist_resources: userId (FK to users.id), tasklistId (FK to tasklists.id)

我正在他们的模型中定义这样的关系:

let bookshelf = require('./base');

var User,
    Users;

User = bookshelf.Model.extend({
    tableName: 'users',
    taskLists: function() {
        return this.belongsToMany('TaskList', 'tasklist_resources', 'userId', 'tasklistId');
    }
});

Users = bookshelf.Collection.extend({
    model: User
});

module.exports = {
    User: bookshelf.model('User', User),
    Users: bookshelf.collection('Users', Users)
};

而且:

let bookshelf = require('./base');

var TaskListResource,
    TaskListResources;

TaskListResource = bookshelf.Model.extend({
    tableName: 'tasklist_resources',
    users: function() {
        return this.belongsToMany('User', 'tasklist_resources', 'tasklistId', 'userId');
    }
});

TaskListResources = bookshelf.Collection.extend({
    model: TaskListResource
});

module.exports = {
    TaskListResource: bookshelf.model('TaskListResource', TaskListResource),
    TaskListResources: bookshelf.collection('TaskListResources', TaskListResources)
};

然后,如果在连接表中找到该行,我正在尝试返回完整的用户信息:

new TaskListResource({
                tasklistId: req.params.tasklistId,
                userId: req.params.id
            })
            .fetch({
                withRelated: [ 'users' ]
            })
            .then(result => {
                res.status(200).json(result);
            })

但它只返回tasklist_resources表中的值(例如[{"tasklistId":1,"userId":1}])。我错过了什么?

1 个答案:

答案 0 :(得分:0)

通过使用TaskList模型来检索与taskList关联的资源(用户)。

let bookshelf = require('./base');

var TaskList,
    TaskLists;

TaskList = bookshelf.Model.extend({
    tableName: 'tasklists',
    createdByUser: function () {
        return this.belongsTo('User', 'createdBy');
    },
    resources: function() {
        return this.belongsToMany('User', 'tasklist_resources', 'tasklistId', 'userId', 'id');
    }
});

TaskLists = bookshelf.Collection.extend({
    model: TaskList
});

module.exports = {
    TaskList: bookshelf.model('TaskList', TaskList),
    TaskLists: bookshelf.collection('TaskLists', TaskLists)
};

并选择数据:

new TaskList({
                id: req.params.tasklistId
            })
            .fetch({ withRelated: ['resources'] })
            .then(result => {
                res.setHeader('X-InlineCount', result.related('resources').length);
                res.setHeader('Access-Control-Expose-Headers', 'X-InlineCount');

                res.json(result.related('resources'));
            })