2017-07-07 79 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,這樣列將不存在。 而且會比使用鉤子更清潔。