如何在sequelize中定义关联和查询Self-Referencing Table?

how to define associations and query Self-Referencing Table in sequelize?

我正在重新编写一个应用程序以利用 sequelize。到目前为止,在文档的帮助下。我创建了以下具有关联的模型。员工 table 是自引用的,并且有一个 managerid 列指向员工 table 的 ID。如何创建关联并查询此类 table,同时将其与其他 table 等地址加入?

 

员工模型

var employee = db.seq.define('Employee',{
    id: { type: db.Sequelize.INTEGER},
    managerId: { type: db.Sequelize.INTEGER}, 
    employee_name: { type: db.Sequelize.STRING}
    ...
});
employee.hasOne(address); 

地址模型

var adress= db.seq.define("Adresss",{
    employee_id: { type: db.Sequelize.INTEGER},
    ...
});
address.belongsto(employee); 

belongsTo 关联添加到具有别名的同一模型:

employee.belongsTo(employee, { foreignKey: 'managerId', as: 'Manager' }); 

现在您可以获得一名员工以及一名相关经理:

const found = await employee.findById(id, {
  include: [{
    model: employee,
    as: 'Manager'
  }, address]
});