2017-10-04 26 views
0

我使用sequelize为node.js中我定义这种关系:如何更改和保存模型实例的关联?

// 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正确设置。但是,如果我去数据库没有什么改变。没有什么是真的保存。

回答

0

哎呀刚刚发现了这个问题。当设置这样的关联时,你不应该使用set()方法。相反,sequelize会为每个关联创建setter。在我而言,我不得不使用setGovernance_status():

// Update corresponding foreign keys 
    result.setGovernance_status(answer[0]) 

如果有人在那里这是记录在文档中的任何地方发现我将不胜感激:)

相关问题