【问题标题】:Let sailsJS auto update createdAt and updatedAt让sailsJS自动更新createdAt和updatedAt
【发布时间】:2018-01-31 09:49:36
【问题描述】:

我正在尝试设置一个具有 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 设置为安全,这样每次启动时都不会清除表。)

migrate: 'safe',

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

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

但是,当我开始使用sails 时,表格已经存在,所以我不确定这些东西是否只有在您使用sails 创建表格时才有效。

【问题讨论】:

  • 我有同样的问题,我没有找到任何解决方案。我认为这是一个已知的水线错误。我的解决方案是,当我使用 SQL 创建表时,这样做。

标签: mysql sails.js


【解决方案1】:

要将这些应用于所有表,您可以修改 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

【讨论】:

    【解决方案2】:

    在 USER 模型中进行以下更改

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-07
      • 2018-02-13
      • 2019-07-19
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 2022-12-02
      • 2018-10-08
      相关资源
      最近更新 更多