Home > Blockchain >  I tried to add self reference relationship using Sequelize
I tried to add self reference relationship using Sequelize

Time:03-09

There is a table called employees and the employee id wants to self reference to the employee table when the employee has a team lead.

Team lead is also an employee. So how to self reference using Sequelize?

const Employee = sequelize.define("employee", {
id: {
  type: DataTypes.INTEGER,
  autoIncrement: true,
  primaryKey: true,
  allowNull: false,
},
first_name: {
  type: DataTypes.STRING(45),
  allowNull: false,
},
lead_role: {
  type: DataTypes.BOOLEAN,
  allowNull: false,
  defaultValue: false,
},
designation: {
  type: DataTypes.STRING(100),
  allowNull: true,
},
resignation_date: {
  type: DataTypes.DATE,
  allowNull: true,
},
lead_id: {
  type: DataTypes.INTEGER,
  allowNull: true,
},
});

this is my employee model associations

 Employee.associate = function (models) {
   Employee.hasOne(models.user, { foreignKey: "employee_id" });
   Employee.hasMany(models.leave_request, {
    foreignKey: "employee_id",
   });
   Employee.belongsTo(models.team, {
    foreignKey: "team_id",
   });
   Employee.belongsTo(models.team_manager, {
    foreignKey: "manager_id",
   });
   Employee.hasMany(models.attendance, {
    foreignKey: "employee_id",
   });
   Employee.belongsTo(models.employee, {
     foreignKey: "lead_id",
   });
   Employee.hasMany(models.employee, {
     foreignKey: "lead_id",
   });
 };



 

CodePudding user response:

You just need to indicate aliases for both a team lead link and employees link:

Employee.belongsTo(models.employee, {
     foreignKey: "lead_id",
     as: 'TeamLead'
   });
   Employee.hasMany(models.employee, {
     foreignKey: "lead_id",
     as: 'TeamEmployees'
   });

And you need to indicate the same aliases in queries:

const employees = await Employee.findAll({
  where: {
    team_id: teamId
  },
  include: [{
    model: Employee,
    as: 'TeamLead'
  }]
})
const teamLead = await Employee.findAll({
  where: {
    id: teamLeadId
  },
  include: [{
    model: Employee,
    as: 'TeamLead'
  }]
})
  • Related