You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

knex绑定数组执行havingRaw查询报错Expected 4 bindings, saw 1如何解决

报错原因

你调用havingRaw时传入的绑定参数是长度为4的数组[3,16,17,18],knex默认会把传入的绑定数组中的每一项对应一个?占位符。而你的SQL语句里只写了1个?,knex解析时发现绑定参数有4个,占位符只有1个,两者数量不匹配,就抛出了Expected 4 bindings, saw 1的错误。

解决方案

你可以根据使用场景二选一:

  • 固定长度数组场景:如果用户ID数组长度是固定的,直接把SQL里的等号右侧改为和数组元素数量对应的array[?, ?, ?, ?]即可,修改后的代码如下:
await knex( 'participants' )
  .select( 'conversation' )
  .groupBy( 'conversation' )
  .havingRaw( 'array_agg(participants.user order by participants.user) = array[?, ?, ?, ?]', [3,16,17,18] )
  • 动态长度数组场景:如果数组长度不固定,不需要手动数占位符数量,可以直接把数组转成PostgreSQL可识别的int数组类型绑定,修改后的代码如下:
const userIds = [3, 16, 17, 18]
await knex( 'participants' )
  .select( 'conversation' )
  .groupBy( 'conversation' )
  .havingRaw( 'array_agg(participants.user order by participants.user) = ?::int[]', [JSON.stringify(userIds)] )

内容的提问来源于stack exchange,提问作者Will

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 16:36:03