当我编译我的节点应用程序试图在模型类中放置许多关系时,会出现此错误
MyModel.hasMany called with something that's not a subclass of Sequelize.Model
这是我的模型类 Poll.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
Question.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
Catchment.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
架构为:
我认为可能是因为它们具有相同的ForeignKey名称:poll_id,谢谢
答案 0 :(得分:1)
我认为问题在于模块之间的循环依赖关系。显然,您是按顺序要求它们的,而相关模型并不能全部那样提供。
定义模型并不导出关联,然后在定义模型后创建关联。
例如:
// 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'});