I'm using sequelize, DB as Postgres
my students table as ( id, name, dept_id ) columns.
my departments table as ( id, dname, hod) columns
My Association while looks like this
Student.hasOne(models.Department, {
foreignKey: 'id',
as : "role"
});
I want to get a student with a particular id and his department details. By using sequelize I wrote a query like below
Student.findOne({
where: { id: id },
include: [{
model: Department,
as:"dept"
}],
})
FYI with this includes option in findOne, it is generated a left outer join query as below
SELECT "Student"."id", "Student"."name", "Student"."dept_id", "dept"."id" AS "dept.id", "dept"."dname" AS "dept.dname", "dept"."hod" AS "dept.hod", FROM "students" AS "Student"
LEFT OUTER JOIN "departments" AS "dept"
ON "Student"."id" = "dept"."id"
WHERE "Student"."id" = 1
LIMIT 1;
My expected Output should be
{
id: 1,
name: "bod",
dept_id: 4,
dept: {
id: 4,
dname: "xyz",
hod: "x"
}
}
but I'm getting
{
id: 1,
name: "bod",
dept_id: 4,
dept: {
id: 1,
dname: "abc",
hod: "a"
}
}
so how to I change ON condition to
ON "Student"."dept_id" = "dept"."id"
thank you in advance
Student.hasOne(models.Department, {
foreignKey: 'dept_id', // fixed
as : "role"
});