温馨提示:本文翻译自stackoverflow.com,查看原文请点击:node.js - Model association in sequelize [erro]{ this.name}.hasMany called with something that's not a subclas
node.js orm postgresql sequelize.js

node.js - sequelize [erro] {this.name} .hasMan中的模型关联以很多子句调用

发布于 2020-05-24 11:12:01

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

错误:Fator.hasMany调用的不是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;
};

型号Sub_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;
};

查看更多

提问者
Tarcisio pieroni
被浏览
7
Fernando Zamperin 2020-03-08 08:13
//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;
};

原因是因为您在此处定义模型,但是随后在您的models / index.js或类似的内容中将其导入以生成对象模型,所以这仅仅是一个模型定义,而不是Sequelize.Model的子类。

PS:如果在项目中生成了续集,则索引应该是这样的:

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