实例报告 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 的新记录
发布评论