【发布时间】:2023-03-28 18:11:01
【问题描述】:
我正在为 node.js 使用 sequelize。我定义了这种关系:
// 1:M - Platform table with Governance status table
dbSchema.Platform_governance.belongsTo(dbSchema.Governance_status, {foreignKey: 'platform_status'});
dbSchema.Governance_status.hasMany(dbSchema.Platform_governance, {foreignKey: 'platform_status'});
这意味着我有一个名为 platform_governance 的表,它有一个指向Governance_status 行的外键。用户想要更改此外键以指向不同的Governance_status 行。
所以我想先搜索用户选择的这个governance_status行确实存在并且是唯一的,然后让外键指向它。这是我目前拥有的:
// first I select the platform_governance of which I want to change it's foreign key
dbSchema.Platform_governance.findById(5, {include: [dbSchema.Governance_status]}).then(result => {
// Now I search for the user-requested governance_status
dbSchema.Governance_status.findAll({where:{user_input}}).then(answer => {
// I check that one and only one row was found:
if (answer.length != 1 ) {
console.log('error')
} else {
// Here I want to update the foreign key
// I want and need to do it through the associated model, not the foreign key name
result.set('governance_status', answer[0])
result.save().then(result => console.log(result.get({plain:true}))).catch(err => console.log(err))
}
result.save() 承诺成功返回,控制台打印的对象是正确的,新的治理状态设置正确。但是如果我去数据库,什么都没有改变。什么都没有真正保存。
【问题讨论】:
标签: node.js sequelize.js