下面是我在 Hooks 中用于更新两个对象的 updatedAt 列的代码:

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 列?

最佳答案

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

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

10-08 19:48