首页 > 解决方案 > 具有自定义 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"

先感谢您

标签: node.jspostgresqlsequelize.jssequelize-cli

解决方案


Student.hasOne(models.Department, {
    foreignKey: 'dept_id', // fixed
    as : "role"
  });

推荐阅读