1

我目前正在使用 Sequelize => 4.0 并且发现将 2 个模型链接在一起并不能像我想象的那样工作。

基本上,我有 2 个模型:用户和打孔。

用户: id 姓名 电子邮件

打孔:id userId <-用户id时间状态

我想显示用户列表及其链接的拳头。

这是我在每个模型下的 .associate 函数:

users.associate = function (models) { // eslint-disable-line no-unused-vars
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/

    users.hasMany( models.punch, {foreignKey: 'id'} );
};


punch.associate = function (models) { // eslint-disable-line no-unused-vars
// Define associations here
// See http://docs.sequelizejs.com/en/latest/docs/associations/

    punch.belongsTo(models.users, {foreignKey: 'userId', targetKey: 'id'});
};

这是正确的方法吗?还有什么我需要做的。当我查看用户 GET 请求时,除了用户数据之外,我没有看到任何其他内容。

任何帮助将不胜感激 :)

4

1 回答 1

1

您需要根据feathers-sequelize docs更新之前的钩子:

// users.hooks.js

associationHook(context){
    const PunchModel = context.app.services.punch.Model;

    context.params.sequelize = {
        include: [{ model: PunchModel }]
    }
}

module.exports = {
    before: {
        (...)
        find: [associationHook],
        (...)
    }
    (...)
};

您需要为 find/get 以及您希望返回关联数据的任何其他操作执行此操作。

在feathers-hooks-common 中还有fastJoinpopulate

于 2018-05-04T09:08:40.500 回答