gpt4 book ai didi

node.js - 具有自定义 ON 条件的左外连接 Sequelize

转载 作者:行者123 更新时间:2023-12-03 22:21:01 24 4
gpt4 key购买 nike

我正在使用 sequelize,DB 作为 Postgres
我的学生表为 ( id, name, dept_id ) 列。
我的部门表为 (id, dname, hod) 列
我的协会 while 看起来像这样

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

关于node.js - 具有自定义 ON 条件的左外连接 Sequelize ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64387638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com