Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two foreign Key of same table in one table in sequelize

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.

like image 477
hardy Avatar asked Apr 20 '17 15:04

hardy


1 Answers

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
}]
like image 116
Ellebkey Avatar answered Oct 22 '22 17:10

Ellebkey