Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only createdAt column in join table

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?

like image 396
Ali Sherafat Avatar asked Sep 05 '25 17:09

Ali Sherafat


1 Answers

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.

like image 77
Shivam Avatar answered Sep 08 '25 12:09

Shivam