【问题标题】:left outer join with custom ON condition sequelize具有自定义 ON 条件的左外连接 sequelize
【发布时间】:2021-01-30 21:16:02
【问题描述】:

我正在使用 sequelize,DB as 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.js postgresql sequelize.js sequelize-cli


    【解决方案1】:
    Student.hasOne(models.Department, {
        foreignKey: 'dept_id', // fixed
        as : "role"
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-16
      • 2012-01-08
      • 1970-01-01
      • 2014-11-07
      • 2010-11-10
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多