By default, sequelize will create createdAt and updatedAt columns in join table for many to many relationships but I only want to use createdAt
column and set it automatically when row created.
custom UserJob
model:
const UserJob = sequelize.define('UserJob', {
createdAt: DataTypes.DATE
}, {
timestamps: false
});
UserJob.beforeCreate((userJob, options) => {
console.log('before create');
userJob.createdAt = new Date();
});
return UserJob;
Associations:
User.belongsToMany(models.Job, {through: UserJob, foreignKey: 'user_id'});
Job.belongsToMany(models.User, {through: UserJob, foreignKey: 'job_id'});
it doesn't set createdAt, what should I do?
As sequelize suggests, if you don't want a particular timestamp You should define your model as
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'
})
So for your case, you could set updatedAt
to false, that way the column won't exist.
And would be more cleaner than using a hook.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With