我使用当前的Sequelize版本,并尝试建立两个模型之间的关联。由于Sequelize提供了hasMany
和belongsTo
,因此实际上应该非常简单。
但是通话完全没有效果。我尝试了一个新的SQL DB。表本身是创建的,没有任何外键。
数据库控制器
const userModel = require('../model/user')
const subjectModel = require('../model/subject')
const database = require('../db/database').sequeliceInstance
async function setupAssociations () {
await database.sync()
// user + subject
userModel.hasMany(subjectModel)
subjectModel.belongsTo(userModel)
// subject and topic
subjectModel.hasMany(topicModel)
topicModel.belongsTo(subjectModel)
// topic and question
topicModel.hasMany(questionModel)
questionModel.belongsTo(topicModel)
// question and answer
questionModel.hasMany(answerModel)
answerModel.belongsTo(questionModel)
return Promise.resolve()
}
user.js
const Sequelize = require('sequelize')
const db = require('../db/database').sequeliceInstance
const user = db.define('user', {
// attributes
firstName: {
type: Sequelize.STRING,
allowNull: false
},
lastName: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
allowNull: false
},
title: {
type: Sequelize.STRING,
allowNull: false
},
password: {
type: Sequelize.TEXT,
allowNull: false
}
})
module.exports = user
subject.js
const Sequelize = require('sequelize')
const db = require('../db/database').sequeliceInstance
const subject = db.define('subject', {
// attributes
subjectName: {
type: Sequelize.TEXT,
allowNull: false
}
})
module.exports = subject
答案 0 :(得分:0)
我找到了解决方案。
await database.sync()
必须在函数的最后调用。