如何将postgreSQL转换为Sequelize格式

时间:2019-05-24 06:47:24

标签: node.js postgresql npm sequelize.js

我必须尝试使用​​sequelize npm软件包将postgre sql查询转换为orm概念,请指导我。

select * from "locationDepartmentMappings" as a
inner join "departments" as b on a."departmentId" = b.id
inner join "locations" as c on a."locationId" = c.id
where (
    b."departmentName" like '%Accounting%' or c."locationName" like '%Accounting%'
)
limit 1;

按照下面的代码我仍然可以得到

  

错误:列locationDepartmentMapping.department.departmentName不存在

正如@shivam所述,我尝试过以下操作,请问我需要更改的内容,

        let ldv = await LocationDepartmentModel.findAll({
          include: [
            {
              model: LocationModel,
              as: "location",
              required: true,
            },
            {
              model: DepartmentModel,
              as: "department",
              required: true,
            }
          ],
          where: {
            $or: [
              {
                "department.departmentName": { like: `%${reqQueryName}%` }
              },
              { "location.locationName": { like: `%${reqQueryName}%` } }
            ]
          },
          limit:1
        });

2 个答案:

答案 0 :(得分:0)

Sequelize关于如何使用orm语法编写查询的文档非常不错。 首先,上面的查询类似于

Model.locationDepartmentMappings.findAll({
  include: [
    {
      model: Model.departments
      where: {departmentName: {$like: '% Accounting%'}}
    },
    {
      model: Model.locations
      where: {locationName: {$like: '% Accounting%'}}
    }],
  limit: 1
})

您应该考虑进入上述查询的是
1.了解如何制作续集models
2.学习Associations
3. Querying

这里有很多很棒的教程,可以帮助您入门,而且仅用Google搜索即可!

答案 1 :(得分:0)

最终在帮助下获得了解决方案:

let ldData = await LocationDepartmentModel.findAll({
      include: [
        {
          model: LocationModel,
          as: "location",
          required: true
        },
        {
          model: DepartmentModel,
          as: "department",
          required: true
        }
      ],
      where: {
        $or: [
          { "$department.departmentName$": { like: `%${reqQueryName}%` } },
          { "$location.locationName$": { like: `%${reqQueryName}%` } }
        ]
      },
      limit: 1
    });

由以下提供:

@shivam answer for joining tables

@ManjulSigdel answer for where condition include table column