续集中一张表中同一表的两个外键

时间:2017-04-20 15:01:36

标签: node.js sequelize.js

我的团队成员模型: -

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 ------ employeeId ------ supervisorId

2 ----------- 4 ------------- 5

问题是 - :所以当我要求teamMember中的行,其employeeId为4.应该包含在supervisorId(JOIN)中,并返回包含4(id)的员工的行。我想要第5名员工。

supervisorId和employeeId都是员工表格。

1 个答案:

答案 0 :(得分:10)

您不需要在模型上设置员工和主管的字段,只需执行所有它将添加它,并且您可以在那里指定if是唯一的并使用“as”以便您可以了解员工是你引用加入,普通员工或主管,如下:

db.teamMember.belongsTo(db.employee, {as: 'SupervisorId'});
db.teamMember.belongsTo(db.employee, {as: 'RegularEmployeeId'});

然后在您的查询中添加如下所示的包:

include: [{
    model: db.employee,
    as: 'SupervisorId
}]