简体   繁体   English

当使用Associate时似乎不起作用

[英]belongsTo using associate doesn't seem to work

I have two "models" in my application that are branched into different files: 我的应用程序中有两个“模型”,它们分别分支到不同的文件中:

ApplicationSession.model.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 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;
};

When saving the tables (DROPING/RECREATING) force: true and manual dropping just for sanity, there is never a field created for the user. 当保存表时(拖放/撤消) force: true和手动删除只是出于理智,从来没有为用户创建字段。

Here's how I'm loading my different models 这是我加载不同模型的方式

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;

When all of the models are declared in a single file, I can use X.belongsTo(Y) without any problems, so I thought I'd try adding this to the bottom of my sequelize.import calls 当所有模型都在一个文件中声明时,我可以X.belongsTo(Y)使用X.belongsTo(Y) ,因此我想将其添加到sequelize.import调用的底部。

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

However, that generated a different error: 但是,这产生了另一个错误:

/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) 

What do I do to make relationships work? 我怎样做才能使人际关系正常工作?

You need to add one more thing to your model loading module to make associations work. 您需要在模型加载模块中再添加一件东西,以使关联起作用。

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

I also saw another mistake in your code. 我还看到了您的代码中的另一个错误。 The class method defined in your models associate should be wrapped around classMethods property. 在模型associate定义的类方法应围绕classMethods属性包装。

It should look like this : 它应该看起来像这样:

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

You can follow the examples by sequelize in GitHub . 您可以通过在sequelize下面的例子GitHub上

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM