如何在sequelize中使用子查询来引用self table?

How to use subquery in sequelize to reference self table?

我想用 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 来完成整个事情,但根据 它应该能够在 typescript 支持下编写它。然而,我的情况有所不同,因为我将子查询引用到相同的 table。我创建了以下代码:

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”,但我需要 table 有“t2”作为别名。如果不可能通过 FindOptions 中的任何参数,我可以想象用正则表达式来完成这一切。疯狂但可以做到。

但是“this.pricingRepository.findAll”方法会产生以下错误:

SequelizeDatabaseError: relation "Pricing" does not exist

嗯,定价 table 确实与自身无关,但在子查询中既不需要也不需要。

有没有什么简单的方法或者我应该直接去 rawQuery 并在 SQL 中手动写入所有内容吗?

我终于用两个独立的queryGenerators和regex把它们混在一起了