我的团队成员模特: – var teamMember = { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, level: DataTypes.INTEGER, supervisorId: { type: DataTypes.INTEGER, references: { model: "employees", key: "id" } }, e
var teamMember = { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, level: DataTypes.INTEGER, supervisorId: { type: DataTypes.INTEGER, references: { model: "employees", key: "id" } }, employeeId: { type: DataTypes.INTEGER, unique: true, references: { model: "employees", key: "id" } }
并且有员工模型
制图: –
db.employee.hasOne(db.teamMember); db.teamMember.belongsTo(db.employee);
我的查询功能
db.teamMember.findOne({ where: { employeeId: req.employee.id }, include: [db.employee] }) .then(teamMember => { if (!teamMember) { throw ('no teamMember found'); } consol.log(teamMember) })
我的teamMember表就像=
ID ——雇员—— supervisorId
2 ———– 4 ————- 5
问题是 – :所以当我要求teamMember中的行,其employeeId为4.应该包含在supervisorId(JOIN)中,并返回包含4(id)的员工的行.我想要第5个身份的员工.
supervisorId和employeeId都是员工表.
您不需要在模型上设置员工和主管的字段,只需执行所有它将添加它,并且您可以在那里指定if是唯一的并使用“as”,这样您就可以了解员工是否正在引用加入,正式员工或主管,如下所示:db.teamMember.belongsTo(db.employee, {as: 'SupervisorId'}); db.teamMember.belongsTo(db.employee, {as: 'RegularEmployeeId'});
然后在您的查询中添加如下所示的包含:
include: [{ model: db.employee, as: 'SupervisorId }]