【发布时间】:2021-10-15 14:57:04
【问题描述】:
我想使用 sequelize.queryGenerator 创建简单查询,并通过“文字”将其发送到模型查询以获取结果。基本思想是生成这样的查询:
select * from table t1
where id in (
select id from table t2
where t1.productId = t2.productId
order by t2.validfrom desc limit 1
)
我总是可以对整个事情使用 rawQuery,但根据Sequelize - subquery in where clause 它应该能够在打字稿支持的情况下编写它。然而,当我将子查询引用到同一个表时,我的情况有所不同。我创建了以下代码:
const whereSubquery: FindOptions<Pricing> = {
attributes: ['id'],
where: {
ProductId: 3,
validFrom: new Date(2021, 9, 15),
},
order: [['validFrom', 'desc']],
limit: 1,
};
const subQuery: string = this.queryGenerator
.selectQuery(Pricing.name, whereSubquery)
.slice(0, -1); // to remove the ';' from the end of the SQL
console.log(subQuery);
const result = await this.pricingRepository.findAll({
where: {
id: {
[Op.in]: SequelizeTypeScript.literal(`(${subQuery})`),
},
},
});
console.log 按预期显示查询:
SELECT "id"
FROM "Pricing"
WHERE "Pricing"."ProductId" = 3
AND "Pricing"."validFrom" = '2021-10-15 14:25:59.406 +00:00'
ORDER BY "validFrom"
DESC LIMIT 1
到目前为止一切顺利。我将用文字 t1."ProductId" 替换静态值“3”,但我需要表有“t2”作为别名。如果无法通过 FindOptions 中的任何参数实现,我可以想象使用正则表达式完成所有操作。疯狂但可以做到。
但是“this.pricingRepository.findAll”方法会产生以下错误:
SequelizeDatabaseError: relation "Pricing" does not exist
好吧,定价表确实与其自身没有关系,但在子查询中它不是预期的也不是必需的。
有什么简单的方法或者我应该直接去rawQuery然后用SQL手动写所有东西吗?
【问题讨论】:
标签: sequelize.js