左外连接与自定义 ON 条件续集
left outer join with custom ON condition sequelize
我正在使用 sequelize,DB 作为 Postgres
我的学生 table 作为 ( id, name, dept_id ) 列。
我的部门 table 作为(id、dname、hod)列
我的协会看起来像这样
Student.hasOne(models.Department, {
foreignKey: 'id',
as : "role"
});
我想要获得具有特定 ID 及其部门详细信息的学生。通过使用 sequelize,我编写了如下查询
Student.findOne({
where: { id: id },
include: [{
model: Department,
as:"dept"
}],
})
仅供参考,在 findOne 中包含这个选项,它会生成一个左外连接查询,如下所示
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;
我的预期输出应该是
{
id: 1,
name: "bod",
dept_id: 4,
dept: {
id: 4,
dname: "xyz",
hod: "x"
}
}
但我得到了
{
id: 1,
name: "bod",
dept_id: 4,
dept: {
id: 1,
dname: "abc",
hod: "a"
}
}
那么如何将 ON 条件更改为
ON "Student"."dept_id" = "dept"."id"
提前谢谢你
Student.hasOne(models.Department, {
foreignKey: 'dept_id', // fixed
as : "role"
});
我正在使用 sequelize,DB 作为 Postgres
我的学生 table 作为 ( id, name, dept_id ) 列。
我的部门 table 作为(id、dname、hod)列
我的协会看起来像这样
Student.hasOne(models.Department, {
foreignKey: 'id',
as : "role"
});
我想要获得具有特定 ID 及其部门详细信息的学生。通过使用 sequelize,我编写了如下查询
Student.findOne({
where: { id: id },
include: [{
model: Department,
as:"dept"
}],
})
仅供参考,在 findOne 中包含这个选项,它会生成一个左外连接查询,如下所示
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;
我的预期输出应该是
{
id: 1,
name: "bod",
dept_id: 4,
dept: {
id: 4,
dname: "xyz",
hod: "x"
}
}
但我得到了
{
id: 1,
name: "bod",
dept_id: 4,
dept: {
id: 1,
dname: "abc",
hod: "a"
}
}
那么如何将 ON 条件更改为
ON "Student"."dept_id" = "dept"."id"
提前谢谢你
Student.hasOne(models.Department, {
foreignKey: 'dept_id', // fixed
as : "role"
});