MySQL sequelize.js 时间戳不是日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29652538/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:06:05  来源:igfitidea点击:

sequelize.js TIMESTAMP not DATETIME

mysqlnode.jsdatetimetimestampsequelize.js

提问by ?l?

In my node.js app I have several models in which I want to define TIMESTAMPtype columns, including the default timestamps created_atand updated_at.

在我的 node.js 应用程序中,我有几个模型,我想在其中定义TIMESTAMP类型列,包括默认时间戳created_atupdated_at.

According to sequelize.js' documentation, there is only a DATEdata type. It creates DATETIMEcolumns in MySQL.

根据sequelize.js 的文档,只有一种DATE数据类型。它DATETIME在 MySQL 中创建列。

Example:

例子:

var User = sequelize.define('User', {
... // columns
last_login: {
            type: DataTypes.DATE,
            allowNull: false
        },
...
}, { // options
        timestamps: true
});

Is it possible to generate TIMESTAMPcolumns instead?

是否可以生成TIMESTAMP列?

回答by alucic

Just pass in 'TIMESTAMP' string to your type

只需将“TIMESTAMP”字符串传递给您的类型

module.exports = {
  up: function (queryInterface, Sequelize) {
    return queryInterface.createTable('users', {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
        created_at: {
        type: 'TIMESTAMP',
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
        allowNull: false
      },
      updated_at: {
        type: 'TIMESTAMP',
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
        allowNull: false
      }
    });
  }
};

回答by Nate Stone

According to the Sequelize Documentation, you can set a defaultValue of Sequelize.NOW to create a timestamp field. This has the effect but relies on Sequelize to actually populate the timestamp. It does not create a "CURRENT_TIMESTAMP' attribute on the table.

根据 Sequelize 文档,您可以设置 Sequelize.NOW 的 defaultValue 来创建时间戳字段。这有效果,但依赖 Sequelize 来实际填充时间戳。它不会在表上创建“CURRENT_TIMESTAMP”属性。

var Foo = sequelize.define('Foo', {
    // default values for dates => current time
    myDate: { 
         type: Sequelize.DATE, 
         defaultValue: Sequelize.NOW 
    }
});

So, this does accomplish the end goal of having a timestamp field, but it is controlled through Sequelize and not through the actual database engine.

因此,这确实实现了拥有时间戳字段的最终目标,但它是通过 Sequelize 而不是通过实际的数据库引擎来控制的。

It also appears to work on databases that do not have a timestamp functionality, so that may be a benefit.

它似乎也适用于没有时间戳功能的数据库,因此这可能是一个好处。

Reference URL: http://sequelize.readthedocs.org/en/latest/docs/models-definition/#definition

参考网址:http: //sequelize.readthedocs.org/en/latest/docs/models-definition/#definition

回答by Renish Gotecha

In my case i create model like below

就我而言,我创建如下模型

module.exports = (sequelize, type) => {
    return sequelize.define('blog', {
        blogId: {
          type: type.INTEGER,
          primaryKey: true,
          autoIncrement: true
        },
        text: type.STRING,
        createdAt:{
            type: 'TIMESTAMP',
            defaultValue: sequelize.literal('CURRENT_TIMESTAMP'),
            allowNull: false
        },
        updatedAt:{
            type: 'TIMESTAMP',
            defaultValue: sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
            allowNull: false
        }
    })
}

enter image description here

在此处输入图片说明

回答by jithu

instead of

代替

 type: DataTypes.DATE,

use below code

使用下面的代码

      createdAt: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.fn('NOW'),
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.fn('NOW'),
      },

回答by Siddharth Sunchu

You can also use the moment for creating a timestamp:

您还可以使用时刻来创建时间戳:

const moment = require('moment-timezone');

    createdAt: {
      type: DataTypes.NOW,
      allowNull: false,
      defaultValue: moment.utc().format('YYYY-MM-DD HH:mm:ss'),
      field: 'createdAt'
    },

回答by Andrey Borisko

What I did with sqLiteis extended DataTypeswith my custom sql logic for TIMESTAMPand it worked fine. I'm not 100% sure how the sql syntax should look for MySQL but my guess it's something similar to what I have. Look at example:

我对sqLite 所做的是使用我的TIMESTAMP自定义 sql 逻辑扩展数据类型,它运行良好。我不是 100% 确定 sql 语法应该如何查找 MySQL,但我猜它与我所拥有的类似。看例子:

function (sequelize, DataTypes) {

    var util = require('util');
    var timestampSqlFunc = function () {
        var defaultSql = 'DATETIME DEFAULT CURRENT_TIMESTAMP';
        if (this._options && this._options.notNull) {
            defaultSql += ' NOT NULL';
        }
        if (this._options && this._options.onUpdate) {
            // onUpdate logic here:
        }
        return defaultSql;
    };
    DataTypes.TIMESTAMP = function (options) {
        this._options = options;
        var date = new DataTypes.DATE();
        date.toSql = timestampSqlFunc.bind(this);
        if (!(this instanceof DataTypes.DATE)) return date;
        DataTypes.DATE.apply(this, arguments);
    };
    util.inherits(DataTypes.TIMESTAMP, DataTypes.DATE);

    DataTypes.TIMESTAMP.prototype.toSql = timestampSqlFunc;

    var table = sequelize.define("table", {
        /* table fields */
        createdAt: DataTypes.TIMESTAMP,
        updatedAt: DataTypes.TIMESTAMP({ onUpdate: true, notNull: true })
    }, {
        timestamps: false
    });

};

All you need to do for MySQLis to change SQL type generation in timestampSqlFuncfunction, so for example defaultSqlvariable would be 'TIMESTAMP DEFAULT CURRENT_TIMESTAMP'

对于MySQL,您需要做的就是在timestampSqlFunc函数中更改 SQL 类型生成,因此例如defaultSql变量将是'TIMESTAMP DEFAULT CURRENT_TIMESTAMP'