首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何更改和保存模型实例的关联?

如何更改和保存模型实例的关联?
EN

Stack Overflow用户
提问于 2017-10-04 20:34:21
回答 1查看 298关注 0票数 0

我正在为node.js使用sequelize。我定义这种关系:

代码语言:javascript
复制
// 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行是否确实存在并且是唯一的,然后将外键指向它。这就是我目前的情况:

代码语言:javascript
复制
// 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被正确设置。但如果我去数据库什么都没变。没有什么是真正的拯救。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-04 20:41:26

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

代码语言:javascript
复制
  // Update corresponding foreign keys
  result.setGovernance_status(answer[0])

如果有人在文档中找到任何有文档记录的地方,我将不胜感激:)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46573711

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档