gpt4 book ai didi

javascript - belongsTo 使用 associate 似乎不起作用

转载 作者:行者123 更新时间:2023-12-03 22:41:45 24 4
gpt4 key购买 nike

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

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

用户模型.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;
};

保存表格时(删除/重新创建) 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)

我该怎么做才能让人际关系发挥作用?

最佳答案

您需要在模型加载模块中再添加一件事以使关联起作用。

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属性(property)。

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

您可以按照 GitHub 中的示例进行后续处理.

关于javascript - belongsTo 使用 associate 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40692020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com