簡體   English   中英

通過Knex.js執行POSTGRES LIKE時的語法錯誤

[英]Syntax error when doing POSTGRES LIKE through Knex.js

這給了我一個語法錯誤:

if (searchCode) {
  customerProducts = await customerProducts.andWhere(
    db.sequelize.knex.raw('customer.code LIKE '
      + `%${searchCode}%`)
    );
  }
}

錯誤看起來像這樣:

{"message":"UnknownErrorMiddleware error: select \"CustomerProduct\".\"id\" as \"_id\", \"CustomerProduct\".\"last_delivered\" as \"_lastDelivered\", \"CustomerProduct\".\"margin\" as \"_margin\", \"CustomerProduct\".\"outlier\" as \"_outlier\", \"CustomerProduct\".\"growth\" as \"_growth\", \"CustomerProduct\".\"period\" as \"_period\", \"CustomerProduct\".\"price\" as \"_price\", \"CustomerProduct\".\"active\" as \"_active\", \"CustomerProduct\".\"customer_id\" as \"_customerId\", \"CustomerProduct\".\"product_id\" as \"_productId\", \"CustomerProduct\".\"modified\" as \"_modified\", \"CustomerProduct\".\"month_value\" as \"_monthValue\", \"customer\".\"id\" as \"_customer_id\", \"customer\".\"title\" as \"_customer_title\", \"customer\".\"code\" as \"_customer_code\" from \"customer_products\" as \"CustomerProduct\" inner join \"customers\" as \"customer\" on \"CustomerProduct\".\"customer_id\" = \"customer\".\"id\" where \"product_id\" = $1 and customer.code LIKE %ZOO1% - syntax error at or near \"%\"","level":"info"}

我認為問題在於%ZOO1%附近沒有''但我不知道如何添加。 怎么做,如果這不是問題,那是什么?

您可以像這樣'%${searchCode}%'添加它們。 但是searchCode變量將易於進行sql注入。

不過,您應該使用原始參數綁定功能

db.sequelize.knex.raw('customer.code LIKE ?', [`%${searchCode}%`])

https://knexjs.org/#Raw-Bindings

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM