node.js - 具有自定义 ON 条件的左外连接 sequelize
问题描述
我正在使用 sequelize,DB 作为 Postgres
我的学生表为(id、name、dept_id)列。
我的部门表为(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"
});
推荐阅读
- parsing - 如何使用语言具体语法树获得抽象语法树?
- reactjs - 如何在 react.js 中添加一个从列表中删除项目的按钮
- python - Python websockets:如何为多个路由/路径重用单个 websocket
- mysql - 为什么 case 在 SQL 查询中会产生不同的结果?
- python - 如何使用 scrapy 抓取一个充满 .html 文件的目录?
- c# - 最初在 C# 中的 XAML 中实例化 ViewModel 时如何重新实例化它
- sonarqube - SonarQube 忽略属性
- swift - CreateML 图像分类器“在 10 次迭代中早期收敛”
- r - 更新数据表以反映多项选择 - R Shiny
- sql - Oracle sql 查询到 GROUP BY、ORDER BY 并删除每个 ID 的最旧记录