在连接表中只创build了一列
默认情况下,sequelize将在连接表中创buildcreatedAt和updatedAt列以build立多对多的关系,但是我只想使用createdAt
列,并在创build行时自动设置它。
自定义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,我该怎么办?
如后续表明 ,如果你不想要一个特定的时间戳你应该定义你的模型
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,这样列不会存在。 而且会比使用钩子更清洁。