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

更新模型时如何更新多个关联?

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

    我不知道如何在一个简单的电话中更新标签和组织

    function updateOrganization(db, stats) {
      return function (req, res) {
        let myOrg
    
        db.organization.findOne({
          where: {
            id: req.params.id
          },
          include: ['tags']
        })
          .then(org => {
            myOrg = org
            let promises = []
    
            if (req.body.tags) {
              req.body.tags.forEach(tag => {
                promises.push(org.createTag({ name: tag }))
              })
            }
    
            return Promise.all(promises)
          })
          .then(tags => {
            console.log('tags = ', tags)
    
            return myOrg.setTags(tags) <-- DOES NOT SEEM TO BE WORKING
          })
         .then(updatedOrg => {
           console.log('updatedOrg.get() = ', updatedOrg.get()) <-- DOES NOT CONTAIN NEW TAGS
           console.log('myOrg final = ', myOrg.get()) <-- DOES NOT CONTAIN NEW TAGS
           return res.status(HttpStatus.OK).send(myOrg)
          })
          .catch(err => {
            req.log.error(err)
            return handleErr(res, HttpStatus.INTERNAL_SERVER_ERROR, err.message)
          })
      }
    }
    

    注 例如它看起来像一条线 promises.push(org.createTag({ name: tag })) 实际上是在创建标签和线条 return myOrg.setTags(tags) 没有必要。当我拿着一个 findOne updatedOrg

    2 回复  |  直到 7 年前
        1
  •  1
  •   Gamote    7 年前

    function updateOrganization(db, stats) {
      return async (req, res) => {
        try {
          // Get the organization + associations
          const org = await Organization.find({
            where: { id: req.params.id },
            include: ['tags'],
            limit: 1, // added this because in the 4.42.0 version '.findOne()' is deprecated
          });
    
          // Check if we have any tags specified in the body
          if(req.body.tags) {
            await Promise.all(req.body.tags.map(tag => org.createTag({ name: tag })));
          }
    
          return res.status(HttpStatus.OK).send(org.reload()); // use '.reload()' to refresh associated data
        } catch(err) {
          req.log.error(err);
          return handleErr(res, HttpStatus.INTERNAL_SERVER_ERROR, err.message);
        }
      }
    }
    

    .reload() here

    此外,我建议您在将来使用Sequelize事务,这将非常容易控制您的应用程序流。

        2
  •  0
  •   Old Pro    7 年前

    belongsToMany

    无论如何,我相信 createTag 仅当标记不存在时才有效。如果标记存在,则需要 setTags addTags ,传递标记对象或其主键ID。