0

I am using Sequelize ORM. how to set multiple columns in join table? for example -

const UsersTasks = sequelize.define('UsersTasks', {
  id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true },
  userId: {
    type: Sequelize.INTEGER,
    references: {
      model: User,
      key: 'id',
    },
  },
  remarks: { type: Sequelize.STRING(128), allowNull: true },
  taskId: {
    type: Sequelize.INTEGER,
    references: {
      model: Task,
      key: 'id',
    },
  },
}, {
  timestamps: false,
  version: true,
});

User.belongsToMany(Task, {
  through: {
    model: UsersTasks,
    unique: false,
  },
  foreignKey: 'userId',
  as: 'task',
});

Task.belongsToMany(User, {
  through: {
    model: UsersTasks,
    unique: false,
  },
  foreignKey: 'taskId',
});

How can create user - task relationships in UsersTasks?

User.setTask([1,2], {remarks: 'type1'}); User.setTask([1,3], {remarks: 'type2'});

Is this the right way to insert records as following?

id    userId    taskId    remarks
1     1         1         'type1'
2     1         2         'type1'
3     1         1         'type2'
4     1         3         'type2'
hrushilok
  • 435
  • 2
  • 5
  • 20
  • this is not Sequelize problem, is a SQL issue. When you need a relationship M:N, in your case User M : N Task, the table generated UsersTask **can't** have an id, it uses the userId and taskId as a combined one , the logical primary key for this table is formed from the two foreign keys. – Ellebkey Mar 09 '18 at 22:35
  • Okay. then how should I model it? any leads. – hrushilok Mar 12 '18 at 06:39
  • As I see on you data example, you're repeating id from task and remarks, so in yor TasksUsers Model use `belongsTo` instead of `belongsToMany` – Ellebkey Mar 12 '18 at 17:44
  • like this? `UsersTasks.belongsTo(User, { foreignKey: 'userId', targetKey: 'id' });` and `UsersTasks.belongsTo(Task, { foreighKey: 'taskId', targetKey: 'id' });` – hrushilok Mar 14 '18 at 04:44
  • yep, that way you have `UsersTasks` with a PK `id` and two FK – Ellebkey Mar 14 '18 at 18:35

0 Answers0