javascript - Knex 的 `.where()` 不允許傳入單一字串
我在一個使用 Knex 和 SQLite 撰寫的 Node.js 程式中有以下這一行:
await db.table("books")
.innerJoin("items", "items.id", "books.item_id")
.with("idx", db.raw(`instr(items.name, ?) asc`, name))
.where("idx > 0")
.orderBy("idx")
.select()
其中 db 是透過呼叫 knex(config) 所建立的變數。然而,函式 raw(sql) 似乎無法運作,因為它在執行時持續拋出以下錯誤:
TypeError:不允許使用操作符 "undefined" 於 Formatter.operator (I:\git\server\node_modules\knex\lib\formatter.js:138:13)
在 QueryCompiler_SQLite3.whereBasic (I:\git\server\node_modules\knex\lib\query\compiler.js:525:100)
在 QueryCompiler_SQLite3.where (I:\git\server\node_modules\knex\lib\query\compiler.js:314:32)
我做錯了什麼?
如果相關的話,我是使用 Typescript 撰寫的,如你所見使用了 await,我正在使用 ES6。然而,如果我排除 with(),這個查詢可以正常執行,而 with() 拒絕接受不是由 raw() 創建的東西。
編輯:
如果我測試這個,它顯示問題出在 with() 而不是 raw():
console.log("name: " + name);
console.log("db.raw(name): " + db.raw(`instr(items.name, ?) asc`, name));
產生預期的輸出。
答案#1
結果問題出在 where(),直到我更仔細地檢查堆疊追蹤後才發現。將 .where("idx > 0") 替換為 .where("idx", ">&", 0) 就解決了這個問題。