我正在尝试设置一个具有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 .
然而,当我开始使用帆时, table 已经存在,所以我不确定这些东西是否只有在你创建带帆的 table 时才有效 .
2 回答
在USER模型中进行以下更改
要将这些应用于所有表,可以在
config/models.js
中修改module.exports.models
并添加autoUpdatedAt
和autoCreatedAt
属性 . 此外,请确保类型与数据库中的表示方式一致 . 在Sails中,createdAt
和updatedAt
使用datetime
类型:如果您希望列名称与
updatedAt
和createdAt
的默认名称不同,则应将它们设置为字符串值,该值将是自定义列的名称,而不是将值设置为true
.文件:https://sailsjs.com/documentation/concepts/models-and-orm/model-settings#?autocreatedat