node.js - 如何更改和保存模型实例的关联?

标签 node.js sequelize.js

我正在为 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() promise 成功返回并且控制台中打印的对象是正确的,新的governance_status 设置正确。但是如果我去数据库,什么都没有改变。什么都没有真正保存。

最佳答案

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

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

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

关于node.js - 如何更改和保存模型实例的关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46573711/

相关文章:

reactjs - 即使它不是空的,也返回一个空的 json

sequelize.js - 与包含在 Sequelize 中相关的限制和偏移

sequelize.js - 从 Sequelize 中检索属性

node.js - 从 Typescript 类定义 ExpressJS 路由

javascript - 如何使用 Busboy 检测上传流意外停止

javascript - 如何将 Sails.js 与 Drywall 集成

sequelize.js - sequelize cli 不使用 postgres

node.js - 多次测试运行后的 Sequelizejs/未知关系 "xxx"

node.js - 容器之间的 Docker HTTP 请求

arrays - nodejs 在导入范围内未正确处理文件之间的 var array[] 导出默认值