Sequelize v6 实例报告 Find 的新记录

编程入门 行业动态 更新时间:2024-10-05 01:18:48

Sequelize v6 <a href=https://www.elefans.com/category/jswz/34/1771375.html style=实例报告 Find 的新记录"/>

Sequelize v6 实例报告 Find 的新记录

我正在使用 Sequelize v6,并且我有挂钩,如果更新了表中的特定字段,我想运行这些挂钩。因此,我使用实例的

update
方法,而不是模型的
update
方法,因为它没有洞察模型的先前值(据我所知)。

我从

.findAll()

得到实例
const records = await MyModel.findAll({
    where: {
      val0: requestBody.val0,
      val1: requestBody.val1,
    },
  })

每条记录都有

isNewRecord: true
。为什么是这样?当我尝试更新记录时,这让我非常头疼,因为它一直在插入新记录而不是更新我现有的记录。直到看到 Why doesn't save() work in Sequelize? on SO,我才意识到它正在发生。这不应该默认为“false”因为它来自 finder 函数吗?

下面是我的功能的完整示例:

import express from 'express'

import Database from '../../database'
import { MyModel } from '../../models'

export default async (
  request: express.Request, 
  response: express.Response
): Promise<void> => {
  const requestBody = request.body
  const records = await MyModel.findAll({
    where: {
      val0: requestBody.val0,
      val1: requestBody.val1,
    },
  })
 }

  try {
    await Database.pool.transaction(async (t) => {
      const taskList: Promise<[affectedCount: number]>[] = []
      for (const entry of requestBody) {
        const currentSettings = records.find((instance) => {
          return instance.val2 === entry.val2
        })
        const allSame: boolean[] = [
          entry.val0 === currentSettings.val0,
          entry.val1 === currentSettings.val1,
          entry.val2 === currentSettings.val2,
        ]
        if (allSame.every((x) => x)) {
          continue
        } else {
          currentSettings.isNewRecord = false // <== Mandatory Line otherwise 
          //the update will insert a new record instead of modifying this one
          await currentSettings.update(entry, { transaction: t })
        }
      }

      await Promise.all(taskList)
    })

    // Returned updated data
    response.json({
      data: await MyModel.findAll({
        where: {
          val0: requestBody.val0,
          val1: requestBody.val1,
        },
      }),
    })
  } catch (err) {
    console.log('error updating model', err)
    response.status(500).json({ error: err })
  }
}
回答如下:

更多推荐

Sequelize v6 实例报告 Find 的新记录

本文发布于:2024-05-30 07:48:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770268.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   报告   Sequelize   Find

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!