Sequelize:手动更新updatedAt

时间:2017-02-28 22:04:09

标签: javascript mysql node.js sequelize.js

以下是我在Hooks中使用的代码,用于更新两个对象的hooks: { afterUpdate: (group, options, callback) => { console.log("groudId " + groupId + " options " + options) }, afterCreate: (member, options, callback) => { return new Promise((resolve, reject) => { sequelize.models.Group.findOne({ where: { id: member.group_id } }).then((group) => { if (group) { var date = new Date(); console.log("BEFORE group.updatedAt " + group.updatedAt) group.dataValues.updatedAt = new Date() console.log("CHANGED group.updatedAt " + group.updatedAt) group.save().then((Group) => { if (Group) { console.log("UPDATED Group.updatedAt " + Group.updatedAt) console.log("UPDATED group.updatedAt " + group.updatedAt) resolve(Group) } else { console.log("NO GROUP Found") return reject(group.id) } }).catch((error) => { return (error) }) } else { return reject(id) } }).catch((error) => { return (reject) }) }) } 列:

BEFORE group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800 (PST)
CHANGED group.updatedAt Tue Feb 28 2017 14:00:17 GMT-0800 (PST)
UPDATED Group.updatedAt Tue Feb 28 2017 14:00:17 GMT-0800 (PST)
UPDATED group.updatedAt Tue Feb 28 2017 14:00:17 GMT-0800 (PST)
BEFORE group.updatedAt Fri Feb 17 2017 17:36:00 GMT-0800 (PST)
CHANGED group.updatedAt Tue Feb 28 2017 14:00:19 GMT-0800 (PST)
UPDATED Group.updatedAt Tue Feb 28 2017 14:00:19 GMT-0800 (PST)
UPDATED group.updatedAt Tue Feb 28 2017 14:00:19 GMT-0800 (PST)

控制台日志:

updatedAt

虽然我认为日志显示正确,但为什么数据库中的实际对象没有更新为新的updatedAt值?或者是否有更简单的方式来更新对象dset.out <- dset[seg.var == value,]列?

6 个答案:

答案 0 :(得分:1)

这对我有用

group.changed('updatedAt', true)

await group.update({
    updatedAt: new Date()
})

仅用updatedAt = new Date进行更新是不够的,您必须将列标记为已更改

答案 1 :(得分:0)

Accodrding to the docs,您可以通过调用instance.set(key, value, [options])来更新实例值,因此,在您的情况下,它应该是:

console.log("BEFORE group.updatedAt " + group.updatedAt)
group.set('updatedAt', new Date())
console.log("CHANGED group.updatedAt " + group.updatedAt)
group.save().then((Group) => { /* the other part of your code*/ })

答案 2 :(得分:0)

以下工作:

group.changed('updatedAt', true)

这会将updatedAt列标记为脏,以便更新。

答案 3 :(得分:0)

以上都不适合我,所以我不得不改用模型方法:

await MyModel.update({ updatedAt }, { where: { id: instance.id }, silent: true });

答案 4 :(得分:0)

我对Alexander Zinchuk的代码做了一些小改动,对我来说很有效:

await MyModel.update({ updatedAt: new Date() }, { where: { id: instance.id }})

答案 5 :(得分:0)

我能够使用 .changed() 方法更新模型实例上的 updatedAt 属性。这仅在您将两个属性实例设置为 changed = true 时才有效

group.changed('updatedAt', true)
group.changed('exampleProperty', true)
await group.save({ silent: false })