【问题标题】:How to change and save the association of a model instance?如何更改和保存模型实例的关联?
【发布时间】: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


    【解决方案1】:

    糟糕,刚刚发现问题。在设置这样的关联时,您不应该使用 set() 方法。相反,sequelize 为每个关联创建设置器。就我而言,我不得不使用 setGovernance_status():

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

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

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多