默认情况下,sequelize 将在连接表中为多对多关系创建createdAt 和updatedAt 列,但我只想使用createdAt
列并在创建行时自动设置它。
自定义UserJob
模型:
const UserJob = sequelize.define('UserJob', {
createdAt: DataTypes.DATE
}, {
timestamps: false
});
UserJob.beforeCreate((userJob, options) => {
console.log('before create');
userJob.createdAt = new Date();
});
return UserJob;
协会:
User.belongsToMany(models.Job, {through: UserJob, foreignKey: 'user_id'});
Job.belongsToMany(models.User, {through: UserJob, foreignKey: 'job_id'});
它没有设置createdAt,我该怎么办?
最佳答案
如sequelize suggests ,如果您不想要特定的时间戳 您应该将模型定义为
const Foo = sequelize.define('foo', { /* bla */
{ // don't forget to enable timestamps!
timestamps: true,
// I don't want createdAt
createdAt: false,
// I want updatedAt to actually be called updateTimestamp
updatedAt: 'updateTimestamp'
})
因此,对于您的情况,您可以将 updatedAt
设置为 false,这样该列将不存在。
并且比使用钩子(Hook)更干净。
关于node.js - 连接表中仅创建了列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44964176/