Double association with sequelize

1

I have the following relation with the sequelize

// Tasks.js

sequelize.models.tasks.belongsTo(sequelize.models.users, {
	foreignKey: {
		type: DataTypes.INTEGER,
		field: 'ASSIGNEE',
		allowNull: true
	},
	as: 'assignee'
});

sequelize.models.tasks.belongsTo(sequelize.models.users, {
	foreignKey: {
		type: DataTypes.INTEGER,
		field: 'REPORTER',
		allowNull: true
	},
	as: 'reporter'
});

// Users.js

sequelize.models.users.hasMany(sequelize.models.tasks, { as: 'assignee' });
sequelize.models.users.hasMany(sequelize.models.tasks, { as: 'reporter' });

However, what I need is that, in my Tasks table, I only have 2 columns with FK (ASSIGNEE and REPORTER). The problem is that sequelize creates these columns, but creates a 'userId' as well.

Is it possible to do this relationship between the same models with 2 different columns?

    
asked by anonymous 08.01.2017 / 14:12

1 answer

1

I believe this is not the ideal way to define relationships, describing foreignKey at this time.

The Sequelize examples usually do:

const User = sequelize.define('User') // campo id é default

const Task = sequelize.define('Task', {
  name: DataTypes.STRING, // exemplo
  reporterId: {
    type: DataTypes.INTEGER,
    field: 'REPORTER',
    allowNull: true
  },
  assigneeId: {
    type: DataTypes.INTEGER,
    field: 'ASSIGNEE',
    allowNull: true
  }
})

Task.belongsTo(User, {
  foreignKey: 'reporterId',
  as: 'Reporter'
})

Task.belongsTo(User, {
  foreignKey: 'assigneeId',
  as: 'Assignee'
})

What results in the possibility of doing the following query:

return Task.findAll({
  include: [
    {
      model: User,
      as: 'Reporter'
    },
    {
      model: User,
      as: 'Assignee'
    }
  ]
})
.then(tasksArray => {
  console.log(tasksArray[0])
  // { name: <teste>, Reporter: {id: <userId_1>}, Assignee: {id: <userId_2>}
})

Then, by answering the question, Sequelize can create a default field for the Task.belongsTo(User) relationship just named userId . To avoid this it is necessary to define the field in the Task template before establishing the relationship (see my example).

Remembering that it is only necessary to define the relationship of User.hasMany(Task) if it is to perform the query accordingly, working in the same way as the example above.

    
03.04.2017 / 21:07