gpt4 book ai didi

node.js - sequelize [erro]{ this.name}.hasMany 中的模型关联调用不是 Sequelize.Model 的子类

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

我尝试创建一个项目并使用 node.js + sequelize,该项目有两个模型 Fator 和 Sub_fator。他们有一个关联 1:N,但是当创建 fator 时,返回一个错误:

Error: Fator.hasMany called with something that's not a subclass of Sequelize.Model



解决错误的任何建议?

模型因子

'use strict';
const Sub_Fator = require('./sub_fator');

module.exports = (sequelize, DataTypes) => {
const Fator = sequelize.define('Fator', {
descricao: DataTypes.STRING
}, {});
Fator.associate = function(models) {
Fator.hasMany(Sub_Fator, {
foreignKey: 'fatorId',
as: 'fatores'
});
};
return Fator;
};

模型子因子

'use strict';
const Fator = require('./fator');

module.exports = (sequelize, DataTypes) => {
const Sub_Fator = sequelize.define('Sub_Fator', {
fatorId: DataTypes.INTEGER,
descricao: DataTypes.STRING
}, {});
Sub_Fator.associate = function(models) {
Sub_Fator.belongsTo(Fator, {
foreignKey: 'fatorId',
as: 'fatores'
});
};
return Sub_Fator;
};

最佳答案

//Removed this import because is not an object of Model it's a definition
module.exports = (sequelize, DataTypes) => {
const Fator = sequelize.define('Fator', {
descricao: DataTypes.STRING
}, {});
Fator.associate = function(models) {
Fator.hasMany(models.Sub_Fator, {//Change to this instead of Sub_Fator
foreignKey: 'fatorId',
as: 'fatores'
});
};
return Fator;
};

原因是因为你在这里定义了模型,但是在你的模型/index.js 或类似的东西中你必须导入它来生成一个对象模型,这只是一个模型定义,它不是 Sequelize.Model 的子类。

PS:如果你在你的项目中生成了 sequelize,你的索引应该是这样的:
'use strict';

var fs = require('fs');
var path = require('path');
var Sequelize = require('sequelize');
var basename = path.basename(module.filename);
var env = process.env.NODE_ENV || 'development';
var config = require(__dirname + '/../config/server-config.json')[env];
var db = {};

if (config.use_env_variable) {
var sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
.readdirSync(__dirname)
.filter(function(file) {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach(function(file) {
var model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});

Object.keys(db).forEach(function(modelName) {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

关于node.js - sequelize [erro]{ this.name}.hasMany 中的模型关联调用不是 Sequelize.Model 的子类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60577372/

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