顺序关联功能无效

时间:2019-04-23 22:48:08

标签: javascript sequelize.js

我使用当前的Sequelize版本,并尝试建立两个模型之间的关联。由于Sequelize提供了hasManybelongsTo,因此实际上应该非常简单。

但是通话完全没有效果。我尝试了一个新的SQL DB。表本身是创建的,没有任何外键。

enter image description here

数据库控制器

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

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。

await database.sync()必须在函数的最后调用。