belongsTo using associate似乎不起作用

时间:2016-11-19 10:53:43

标签: javascript sequelize.js

我的应用程序中有两个“模型”,它们分支到不同的文件中:

ApplicationSession.model.js

module.exports = function(sequelize, DataTypes) {

    const { INTEGER, DATE } = DataTypes;

    var ApplicationSession = sequelize.define("applicationSession", {
        sessionStart: DATE,
        sessionEnd: DATE
    }, {
        associate: (models) => {
            ApplicationSession.belongsTo(models.User, {
                foreignKey: 'userId',
                as: 'User',
            });
        }
    });

    return ApplicationSession;
};

User.model.js

module.exports = function(sequelize, DataTypes) {

    const { STRING, INTEGER, DATE } = DataTypes;

    var User = sequelize.define("user", {
        name: STRING
    }, {
        associate: (models) => {
            User.hasMany(models.ApplicationSession);
        }
    });

    return User;
};

保存表格(DROPING / RECREATING)force: true并仅为了理智而手动删除时,永远不会为用户创建字段。

以下是我加载不同模型的方法

import fs from 'fs';
import path from 'path';
import sequelize from '../connection';
var exports = {};

fs.readdirSync(__dirname).forEach(fileName => {
    if(~fileName.indexOf('.model.js')) {
        const subname = fileName.replace('.model.js', '');

        const model = sequelize.import(path.join(__dirname, fileName));
        exports[subname] = model;
    }

});

export default exports;

当所有模型都在一个文件中声明时,我可以毫无问题地使用X.belongsTo(Y),所以我想我会尝试将其添加到我sequelize.import调用的底部

    exports['ApplicationSession'].belongsTo(exports['User'], { as: 'User', foreignKey: 'userId' });
    exports['User'].hasMany(exports['ApplicationSession']);

然而,这产生了不同的错误:

/node_modules/sequelize/lib/associations/mixin.js:96
      throw new Error(this.name + '.' + Utils.lowercaseFirst(Type.toString()) + ' called with something that\'s not an instance of Sequelize.Model');
      ^

Error: applicationSession.function BelongsTo(source, target, options) 

如何让关系发挥作用?

1 个答案:

答案 0 :(得分:0)

您需要向模型加载模块添加一个以使关联起作用。

fs.readdirSync(__dirname).forEach(fileName => {
    if(~fileName.indexOf('.model.js')) {
        const subname = fileName.replace('.model.js', '');
        const model = sequelize.import(path.join(__dirname, fileName));
        exports[subname] = model;
    }
});

// You need to check for every model if it has `associate` class method
// and execute it
Object.keys(exports).forEach(function(modelName) {
  if ("associate" in exports[modelName]) {
    exports[modelName].associate(db);
  }
});

我还看到了代码中的另一个错误。模型associate中定义的类方法应该包含classMethods属性。

它应该是这样的:

var ApplicationSession = sequelize.define("applicationSession", {
    sessionStart: DATE,
    sessionEnd: DATE
}, {
    // Add this 
    classMethods: {
        associate: (models) => {   
            ApplicationSession.belongsTo(models.User, {
                foreignKey: 'userId',
                as: 'User',
            });
        }
    }
});

您可以按GitHub中的sequelize按照示例进行操作。