node.js 如何在时间戳上使用“NOW()”更新 Sequelize?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28414395/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update with Sequelize with 'NOW()' on a timestamp?
提问by Blaher
I'm trying to do something like the following:
我正在尝试执行以下操作:
model.updateAttributes({syncedAt: 'NOW()'});
Obviously, that doesn't work because it just gets passed as a string. I want to avoid passing a node constructed timestamp, because later I compare it to another 'ON UPDATE CURRENT_TIMESTAMP' field and the database and source could be running different times.
显然,这不起作用,因为它只是作为字符串传递。我想避免传递节点构造的时间戳,因为稍后我将它与另一个“ON UPDATE CURRENT_TIMESTAMP”字段进行比较,并且数据库和源可能运行不同的时间。
Is my only option to just make a database procedure and call that?
我唯一的选择是创建一个数据库过程并调用它吗?
回答by srlm
You can use Sequelize.fnto wrap it appropriately:
您可以使用Sequelize.fn它来适当地包装它:
instance.updateAttributes({syncedAt: sequelize.fn('NOW')});
Here's a full working example:
这是一个完整的工作示例:
'use strict';
var Sequelize = require('sequelize');
var sequelize = new Sequelize(/*database*/'test', /*username*/'test', /*password*/'test',
{host: 'localhost', dialect: 'postgres'});
var model = sequelize.define('model', {
syncedAt: {type: Sequelize.DATE}
});
sequelize.sync({force: true})
.then(function () {
return model.create({});
})
.then(function () {
return model.find({});
})
.then(function(instance){
return instance.updateAttributes({syncedAt: sequelize.fn('NOW')});
})
.then(function () {
process.exit(0);
})
.catch(function(err){
console.log('Caught error! ' + err);
});
That produces
那产生
UPDATE "models" SET "syncedAt"=NOW(),"updatedAt"='2015-02-09 18:05:28.989 +00:00' WHERE "id"=1
回答by user2643726
Worth mentioning (for people coming here via search) that NOW() isn't standard and doesn't work on SQL server - so don't do this if you care about portability.
值得一提的是(对于通过搜索来到这里的人)NOW() 不是标准的并且不能在 SQL 服务器上运行 - 所以如果您关心可移植性,请不要这样做。
sequelize.literal('CURRENT_TIMESTAMP')
may work better
可能工作得更好
回答by Arthur Mastropietro
you can use: sequelize.literal('CURRENT_TIMESTAMP').
Example:
你可以使用:sequelize.literal('CURRENT_TIMESTAMP')。例子:
await PurchaseModel.update( {purchase_date : sequelize.literal('CURRENT_TIMESTAMP') }, { where: {id: purchaseId} } );

