mysql - 让 sailsJS 自动更新createdAt和updatedAt

标签 mysql sails.js

我正在尝试建立一个具有createdAt和updatedAt列的模型,并希望sails在条目更改时自动更新这些字段。目前我无法让它工作。尝试查看文档,但他们没有提供有关如何设置的“指南”。

我的文件如下:

Users.js(模型)

module.exports = {
  tableName: 'users',
  primaryKey: 'id',
  attributes: {
    id: {
      type:'number',
      unique:true,
      autoIncrement:true
    },
    name: {
      type:'string'
    },
    email: {
      type:'string'
    },
    password: {
      type:'string'
    },
    profilePicture: {
      type:'longtext'
    },
    location: {
      type:'string'
    },
    createdAt: {
      type:'number'
    },
    updatedAt:{
      type: 'number'
    }

  }

};

config.model.js(将迁移设置为安全,这样它就不会在每次启动时清除表。)

migrate: 'safe',

attributes: {
    createdAt: { type: 'number', autoCreatedAt: true, },
    updatedAt: { type: 'number', autoUpdatedAt: true, },
    id: { type: 'number', autoIncrement: true, },
  },

在我的数据库(MySQL)中,我将createdAt和updatedAt列设置为DATETIME。

然而,当我开始使用 sails 时, table 已经存在,所以我不确定这个东西是否只有在你创建带有 sails 的 table 时才起作用。

最佳答案

要将这些应用到您的所有表,您可以修改 config/models.js 中的 module.exports.models 并添加 autoUpdatedAtautoCreatedAt 属性。另外,请确保类型与其在数据库中的表示方式一致。在 Sails 中,createdAtupdatedAt 使用 datetime 类型:

module.exports.models = {
  autoUpdatedAt: true,
  autoCreatedAt: true,

  attributes: {
    createdAt: {
      type: 'datetime',
    }
    updatedAt: {
      type: 'datetime',
    }
  }
}

如果您决定希望列名称与 updatedAtcreatedAt 的默认名称不同,则不要将值设置为 true,您可以将它们设置为一个字符串值,该值将是自定义列的名称。

文档:https://sailsjs.com/documentation/concepts/models-and-orm/model-settings#?autocreatedat

关于mysql - 让 sailsJS 自动更新createdAt和updatedAt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48539089/

相关文章:

php - 当 Wilson 分数间隔相等时,MYSQL 使用 UploadDate 对下一行进行排序

mysql - 在 Windows Vista 上安装 MySQL(使用 IIS)

php - 使用模糊匹配搜索单个 MySQL 文本列

php - ODBC,PHP while 循环将数据分配给数组

mysql - 优先选择 MySQL 中的一行/ID

node.js - 想要在 sails js (mongodb) 中填充集合的计数

javascript - 风 sails js : can't create dummy object on bootstrap with Date attribute

error-handling - 只要 SailsJS 出现错误,Sails 服务器就会关闭

sails.js - Sails JS : How to create model objects from the result of . 查询()?

ssl - Sails JS API SSL/https 支持