node.js - Sequelize : setter for association does not update simple member for it

标签 node.js associations sequelize.js

我有 StudentsClasses,它们之间有 hasMany 关联。
我这样做:

myStudent.setClasses(ids). then(function(result) {
   console.log(myStudent.Classes);
});

问题:
  • result 参数在 then-handler 中是什么意思?
  • 为什么 myStudent.Classes 没有与我所做的 setClasses() 更改保持同步?
  • 如何让 Sequelize 更新简单的 Classes 成员?我需要向调用者返回一个简单的 JSON 响应。
  • 最佳答案

  • 根据 docs ,当将它们发送到 result 方法时, Classes 将是关联的 .setClasses (在你的情况下)。

    因此,您的 ids 参数实际上应该是 Classes ,也许您应该在此之前要求它们
    Class.findAll({where: {id: ids}})
      .on('success', function (classes) {
        myStudent.setClasses(classes)
          .on('success', function (newAssociations) {
            // here now you will have the new classes you introduced into myStudent
            // you say you need to return a JSON response, maybe you could send this new associations
          })
        })
    
  • 它不会更新,因为有关对象关联的查询不依赖于您的原始对象 ( myStudent )。您应该在现有的 result 数组中添加新关联( newAssociations var,在您的示例中为 myStudent.Classes ,在我的示例中)。也许 reloading 您的实例也应该可以工作。
    Class.findAll({where: {id: ids}})
      .on('success', function (classes) {
        myStudent.setClasses(classes)
          .on('success', function (newAssociations) {
            myStudent.Classes = myStudent.Classes || [];
            myStudent.Classes.push(newAssociations);
            // guessing you're not using that myStudent obj anymore
            res.send(myStudent);
          })
      })
    
  • 我希望我用前两个答案回答了这个问题,如果没有,你能通过更新 Classes 成员来解释你的意思吗?
  • 关于node.js - Sequelize : setter for association does not update simple member for it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28044445/

    相关文章:

    javascript - Waterline Sails JS 不起作用

    ruby-on-rails - 检查关联是否存在而不引起数据库命中

    validation - 导轨 6 : How to conditionally validate an association for presence?

    javascript - javascript中的函数相等

    node.js - Mongoose 添加对象数组

    javascript - 如何在 sequelize.js 中正确映射关系的属性?

    mysql - 如何使用 sequelize 用外键值填充表?

    node.js - 在 sequelize 中定义自定义验证

    javascript - 计算机重启后的 TestCafe/Atom 运行结果

    node.js - 如何在 IIS 中托管 Node 应用程序?