我尝试使用 Sequelize 添加自引用关系

I tried to add self reference relationship using Sequelize

有一个叫employees的table,当员工有team lead时,employee id想自引用员工table。

团队负责人也是一名员工。那么如何使用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,
},
});

这是我的员工模型协会

 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",
   });
 };



 

您只需为团队领导 link 和员工 link 指定别名:

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

并且您需要在查询中指明相同的别名:

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'
  }]
})