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.
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
}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With