NodeJS 如何在原始SQL查询中“替换”表名?

gupuwyp2  于 2023-01-04  发布在  Node.js
关注(0)|答案(1)|浏览(148)

我有下面的SQL查询,它的工作:

await sequelize.query(
    "DELETE FROM `table_name` WHERE (?) IN (?)",
    {
        replacements: ["project_id", projectIds],
        type: QueryTypes.DELETE,
    }
);

但我也想使用table_name的替代品,如下所示:

await sequelize.query(
    "DELETE FROM (?) WHERE (?) IN (?)",
    {
        replacements: ["table_name", "project_id", projectIds],
        type: QueryTypes.DELETE,
    }
);

但是这样做不起作用,并且会产生一个关于SQL语法的错误。我怎样才能使它起作用呢?

lyr7nygr

lyr7nygr1#

您混合了数据值绑定和引用标识符。
回购协议中有一个古老的问题:https://github.com/sequelize/sequelize/issues/4494,听起来就像上面的问题。
我相信您可以创建一个考虑不同SQL方言的变通方案,如下所示:

const queryInterface = sequelize.getQueryInterface();

const tableName = queryInterface.quoteIdentifier("projects");
const columnName = queryInterface.quoteIdentifier("project_id");

await sequelize.query(`DELETE FROM ${tableName} WHERE ${columnName} IN (?)`, {
  replacements: [project_ids],
  type: QueryTypes.DELETE,
});

假设您使用的是sequelize 6.x。

相关问题