我通过以下方式绑定到 knex 原始查询来添加订单。
-- Here userIds = [1,2,3] and dataOrder='DESC'
knex.raw.query("
select from users
where userId in ?
order by created ?
",
[
userIds,
dataOrder
])
Run Code Online (Sandbox Code Playgroud)
我收到此错误消息
check the manual that corresponds to your MySQL server version for the right syntax
to use near ''DESC'' at line 1
Run Code Online (Sandbox Code Playgroud)
我尝试使用单引号和双引号的dataOrder 。
当使用 提供 SQL 关键字作为绑定值时.raw(),您需要通过另一个调用来包装该值knex.raw()。我们还需要处理一些更复杂的问题,因为数据库提供者之间没有就数组绑定达成一致。这给我们留下了这样的结果:
const dataOrder = "DESC";
const userIds = [1, 2, 3];
const userIdBindings = userIds.map(_ => "?").join(",");
knex.raw(`
SELECT * FROM users
WHERE id IN (${userIdBindings})
ORDER BY ??
?
`,
[...userIds, "created", knex.raw(dataOrder)]
)
Run Code Online (Sandbox Code Playgroud)
请注意双精度??,因为这表示标识符绑定。
您可能会考虑.raw()尽可能避免,因为您已经发现它很容易出错。考虑:
knex('users')
.whereIn('id', userIds)
.orderBy('created', dataOrder)
Run Code Online (Sandbox Code Playgroud)
简单多了!如果您的实际查询更复杂,请随意发布:使用查询构建器语法可以实现大多数操作。