续集 - 错误许多同名的关系 外键 - MyModel.has许多调用的东西不是 Sequelize.Model 的子类



当我编译节点应用程序试图在我的模型类中放置许多关系时,出现此错误

MyModel.hasMany called with something that's not a subclass of Sequelize.Model

这是我的模型类投票.js

import Sequelize from 'sequelize'
import { sequelize } from '../database/database'
import Catchment from './Catchment'
import Question from './Question'
const Poll = sequelize.define('polls', {
id: {
type: Sequelize.INTEGER,
primaryKey: true
},
title: {
type: Sequelize.TEXT
},
enabled: {
type: Sequelize.BOOLEAN
},
created_at: {
type: 'TIMESTAMP'
},
updated_at: {
type: 'TIMESTAMP'
}
},{
timestamps: false
})
Poll.hasMany(Question, { foreignKey: { name:'poll_id', unique: false}, as: 'questions' })
Poll.hasMany(Catchment, { foreignKey: { name:'poll_id', unique: false}, as: 'catchments' })
export default Poll

问题.js

import Sequelize from 'sequelize'
import { sequelize } from '../database/database'
import Poll from './Poll';
const Question = sequelize.define('questions', {
id: {
type: Sequelize.INTEGER,
primaryKey: true
},
poll_id: {
type: Sequelize.INTEGER
},
title: {
type: Sequelize.TEXT
},
created_at: {
type: 'TIMESTAMP'
},
updated_at: {
type: 'TIMESTAMP'
}
},{
timestamps: false
})
Question.belongsTo(Poll, { foreignKey: { name:'poll_id', unique: false}, as: 'poll' })
export default Question

集水区.js

import Sequelize from 'sequelize'
import { sequelize } from '../database/database'
import Poll from './Poll'
const Catchment = sequelize.define('catchments', {
id: {
type: Sequelize.INTEGER,
primaryKey: true
},
poll_id: {
type: Sequelize.INTEGER
},
created_at: {
type: 'TIMESTAMP'
},
updated_at: {
type: 'TIMESTAMP'
}
}, {
timestamps: false
})
Catchment.belongsTo(Poll, { foreignKey: { name: 'poll_id', unique: false }, as: 'poll' })
export default Catchment

架构为:

  • 投票(有很多(->问题
  • a 民意调查(有许多(->集水区

我认为这可能是因为它们具有相同的外键名称:poll_id,谢谢

我相信问题是模块之间的循环依赖关系。您显然需要按顺序使用它们,并且相关模型不可能都像那样可用。

定义模型并在没有关联的情况下导出,然后在定义模型后创建关联。

例如:

// create the model definitions
const User = require('./user');
const Department = require('./department');
// now that you have the model definitions, create the associations
User.belongsTo(Department, {foreignKey: 'department_id'});
Department.hasMany(User, {foreignKey: 'department_id'});
// or like the below as the models should now exist on sequelize.models
sequelize.models.user.belongsTo(sequelize.models.department, {foreignKey: 'department_id'});
sequelize.models.department.hasMany(sequelize.models.user, {foreignKey: 'department_id'});

最新更新