我正在为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()承诺成功返回,控制台中打印的对象是正确的,新的governance_status被正确设置。但如果我去数据库什么都没变。没有什么是真正的拯救。
发布于 2017-10-04 20:41:26
哎呀,发现问题了。在设置这样的关联时,不应该使用set()方法。相反,sequelize为每个关联创建setter。在我的例子中,我不得不使用setGovernance_status():
// Update corresponding foreign keys
result.setGovernance_status(answer[0])如果有人在文档中找到任何有文档记录的地方,我将不胜感激:)
https://stackoverflow.com/questions/46573711
复制相似问题