sequelize中如何定义关联和查询自引用表?

问题描述 投票:0回答:2

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

 

员工模型

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); 
node.js sequelize.js
2个回答
4
投票

使用别名将

belongsTo
关联添加到同一模型:

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

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

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

0
投票

Anatoly,感谢有用的评论。这对我有用。

© www.soinside.com 2019 - 2024. All rights reserved.