【发布时间】:2020-02-20 23:56:20
【问题描述】:
我有两个与 belongsTo 关系相关联的 Sequelize 模型。我想在创建用户时创建一个 user_sources 实例,但我正在努力完成它。
model_user:
const User = sequelize.define('user', {
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
},
password: {
type: Sequelize.STRING,
allowNull: false
}
}, {
tableName: 'users'
})
model_user_sources:
const UserSources = sequelize.define('user_sources', {
abcNews: {
type: Sequelize.BOOLEAN,
},
bbcNews: {
type: Sequelize.BOOLEAN,
}
}, {
tableName: 'user_sources'
})
UserSources.belongsTo(User)
两个模型都已初始化,并且在数据库中正确创建了表。 According to the Sequelize documentation I should be able to create both with association in a single query 像这样:
User
.create({
email: user.email,
password: user.password,
}, {
include: UserSources
})
但是,仅创建用户。 user_sources 项目不会在表中创建。
不幸的是,该文档仅显示了从子模型创建父模型的示例,而不是相反的示例。我尝试了几种不同的方法,例如使用 hasOne 关联、在 include 中添加模型/关联选项、将数据放入 create 方法等。但我感觉好像我没有正确掌握这个概念。
如果有人能阐明我的问题,将不胜感激。谢谢。
【问题讨论】:
标签: javascript node.js orm sequelize.js associations