Two foreign Key of same table in one table in sequelize

戏子无情 提交于 2019-12-06 03:29:26

问题


my team member model :-

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"
        }
    }

and there is employee model

mapping:-

db.employee.hasOne(db.teamMember);
db.teamMember.belongsTo(db.employee);

my query function

        db.teamMember.findOne({
        where: { employeeId: req.employee.id },
        include: [db.employee]

    })
    .then(teamMember => {
        if (!teamMember) {
            throw ('no teamMember found');
        }
       consol.log(teamMember)
    })

my teamMember table is like=

id------employeeId------supervisorId

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

Problem is -: so when i m asking for row in teamMember whose employeeId is 4. that should be include with supervisorId(JOIN) and it returns row with employee included of 4 (id) . i want employee of 5th id .

Both supervisorId and employeeId are reffer to employee table.


回答1:


You don't need to set the fields of employee and supervisor on the model, just doing the belongTo it will add it, and there you can specify the if is unique and use "as" so you can know with employee are you refering on the join, the regular employee or the supervisor, something like this:

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

and then on your query add the include like this:

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


来源:https://stackoverflow.com/questions/43523203/two-foreign-key-of-same-table-in-one-table-in-sequelize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!