代码之家  ›  专栏  ›  技术社区  ›  Catfish

Sequelize模型关联更新未按预期反映

  •  0
  • Catfish  · 技术社区  · 7 年前

    我正试图通过sequelize将标签与组织关联 set<Model>(...) 方法,它似乎在数据库中正确地设置了标记,但使用这些新标记更新的组织并没有反映这一点。

    组织模式

    'use strict';
    module.exports = (sequelize, DataTypes) => {
      var organization = sequelize.define('organization', {
      ...
      }, {});
      organization.associate = function (models) {
        // associations can be defined here
        organization.hasMany(models.tag)
      };
      return organization;
    };
    

    'use strict';
    module.exports = (sequelize, DataTypes) => {
      ...
      tags.associate = function(models) {
        // associations can be defined here
        tags.belongsTo(models.organization)
      };
      return tags;
    };
    

    方法

    /**
     * Update organization
     * @param {object} db     - The db handle
     * @param {object} stats  - The datadog client
     */
    function updateOrganization(db, stats) {
      return function (req, res) {
    
        let tagsToAdd = []
        let tagsToDelete = []
        let myOrg
    
        db.organization.findOne({
          where: {
            id: req.params.id
          },
          include: ['tags', 'users', 'retrievals']
        })
          .then(org => {
            myOrg = org
            return org.getTags()
          })
          .then(tags => {
            let promises = []
    
            ...a bunch of irrelevant logic
    
            // Add all the new tags
            tagsToAdd.forEach(tag => {
              promises.push(myOrg.createTag({ name: 'newTag' }))
            })
    
            return Promise.all(promises)
          })
          .then(updatedOrg => {
            console.log('updatedOrg = ', updatedOrg) <-- Does NOT have tags in updated org output even though they actually exist in db. Why not???
            return res.status(HttpStatus.OK).send(updatedOrg)
          })
      }
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Catfish    7 年前

    在无数个小时的撞击之后,我终于意识到我需要打电话 reload()

    .then(updatedOrg => {
      console.log('updatedOrg = ', updatedOrg)
      return res.status(HttpStatus.OK).send(updatedOrg)
    })
    

    应该是

    .then(updatedOrg => {
      return myOrg.reload()
    })
    .then(updatedOrg => {
      return res.status(HttpStatus.OK).send(updatedOrg)
    })
    
    推荐文章