簡體   English   中英

更新模型時如何更新 hasMany 關聯?

[英]How to update hasMany associations when updating model?

有沒有辦法在一次調用中更新對象(組織)及其關聯(tasg)? 就我而言,我有 Orgs -> 標簽。 一個組織可以有多個標簽。

我不知道如何在一次簡單的通話中更新標簽和組織

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的輸出?

你可以簡單地使用這樣的東西:

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()更多信息。

另外我建議您將來使用 Sequelize Transactions,它會很容易控制您的應用程序流程。

你確定你想要一個“hasMany”關系。 通常標簽是共享的,組織會有一個“ belongsToMany ”關系。 請發布您的模型和架​​構,如果可能,請發布一個工作示例(使用您的架構連接到數據庫)或一個鏈接。

無論如何,我相信createTag只有在標簽不存在時才會起作用。 如果標簽存在,則需要setTagsaddTags ,傳入標簽對象或其主鍵 ID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM