首页 > 解决方案 > 带有 Knex 的 Postgres - 查询数组包含特定值的位置

问题描述

令人惊讶的是,我无法弄清楚如何使用 knex 返回一个具有包含特定值的数组的表。我在 Postgres 文档中看到这是可能的。

在 sql

SELECT ... FROM fdt WHERE c1 IN (1, 2, 3)

但我无法找到如何使用 knex 完成此操作。网上的一个建议是使用 whereIn。

所以我尝试了

knex.from('pin_table').select('*').whereIn('likes_recieved', id)
 .whereIn('likes_sent', id)

(我还尝试使用数组和搜索参数切换为 whereIn,如 .whereIn(id, 'likes_recieved')

但我不断收到语法错误:

"select * from "pin_table" where "10" in $1 and "10" in $2 - syntax error at or near "$1"

谁能告诉我如何用 knex 或 knex.raw 做到这一点?

谢谢

标签: postgresqlknex.js

解决方案


这在一定程度上取决于您是使用该ARRAY类型,还是likes_sent从子查询等构建。如果它是一个数组,您可能需要使用ANY

knex.from('pin_table').whereRaw('? = ANY(likes_received)', id);

这是没有看到您的架构的最佳猜测。通常我会很想使用单独的表而不是 Postgres 数组:

knex('pin_table as p')
  .join('likes as l', 'p.id', 'l.pin_id')
  .where('l.user_id', id);

有关 Postgres 数组的潜在缺陷和优势的讨论,请参阅https://stackoverflow.com/a/20220450/122643


推荐阅读