postgresql - 带有 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 做到这一点?
谢谢
解决方案
这在一定程度上取决于您是使用该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。
推荐阅读
- linux - 脚本中的逻辑错误
- php - Laravel 5.8 像 4.2 一样在 newQuery 上应用全局范围
- spotfire - 如何在 TIBCO Spotfire 中计算特定日期范围的平均值?
- flutter - Flutter如何在具有堆栈的其他容器上设置容器
- sql - DB2 日期比较
- javascript - 如何在此代码中从左向右滑动文本而不是图像?
- java - Retrofit / Dagger - Android:致命异常:API 声明必须是接口
- azure-active-directory - 量角器网络和 Azure AD
- python - 为什么 vscode 在 python 控制台中执行我的选择如此缓慢?
- node.js - 如何使`query`和`mutation`在graphql中的websocket连接上工作?