【问题标题】:TypeORM - Order By in raw sql dont work with parameterTypeORM - 原始 sql 中的 Order By 不适用于参数
【发布时间】:2019-08-01 20:21:31
【问题描述】:

我正在使用entityManager 和原始查询从 Postgres 数据库中获取数据。我对item_id 的选择和订购有简单的查询。 如果我将完整查询写为:

let query = "Select * From item ... Order By item_id"; 并将其传递给 entityManager await this.entityManager.query(query) order by 工作正常。

但是如果我用参数写查询:

let query = "Select * From item ... Order By $1"; 并将用于排序的 columnName 传递给 entityManager await this.entityManager.query(query,["item_id"]) order by 被完全忽略。

我还尝试将 columName 放入属性并将该属性传递给 entityManager: let columnName = "item_id"; await this.entityManager.query(query,[columnName]) 但结果相同。

我们有 PostgreSql 作为数据库和 typeorm 版本 ^0.2.9

有谁知道,问题可能出在哪里?或者是否有任何解决方法可以在原始 sql 中使用带有参数的 Order By?

提前致谢。

【问题讨论】:

  • 你能把postgresql的日志输出贴出来吗?我们使用 query 方法和准备好的语句,它工作正常。
  • 你到底想从日志中看到什么?
  • postgres 收到的原始 SQL,包括参数。

标签: javascript node.js typescript nestjs typeorm


【解决方案1】:

postgresql 中的ORDER BY 子句不支持准备好的语句。这是因为参数是值而不是标识符。

作为一种变通方法,您可以在 typescript 中使用字符串插值,但最安全的方法是将 SQL 语句包装在一个函数中,并使用 formathere 所述的准备好的语句结合使用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    相关资源
    最近更新 更多