2017-07-07 69 views
1

默认情况下,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,我该怎么办?

+0

它没有得到日期吗?或者在创建没有被调用之前在'userJob.createdAt' –

+0

中插入的内容,并且表中的createdAt为null! –

回答

1

由于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,这样列将不存在。 而且会比使用钩子更清洁。