如何使用 Objection JS 检查数组列是否包含 Postgres 中的值?

How do I check if an array column contains a value in Postgres using Objection JS?

我尝试使用一个整数数组,然后是一个字符串数组。但是,我不断收到相同的错误:

ERROR:  operator does not exist: jsonb ?| integer[]

我的查询如下所示:

Bet.query()
    .select(
        'id', 
        'status'
    )
    .whereJsonSupersetOf('participants_ids', [userId])
    .range()
    .limit(10)   
    .orderBy('id', 'DESC')
    .throwIfNotFound();

这是数组的存储方式:

每个用户都有一个屏幕,他们可以在其中查看自己与其他用户的赌注。为了列出登录用户的投注,我需要检查 participants_ids 列。这是一个数组,其中包含 2 个用户相互投注的 ID。

我查询的目的是 return 一个投注列表,其中当前用户的 ID 包含在每个投注的 participants_ids 数组中。

最初,我尝试了用户 .where().orWhere() 来检查当前用户的 ID 是下注主持人的 ID 还是下注挑战者的 ID。但这并没有给我想要的结果。所以我决定数组列会好得多。

不过我似乎无法让它工作。我看过一些帖子,但它们似乎是对象数组而不是整数或字符串数​​组。我只是想检查 participants_ids 数组列是否包含我传递给查询的 userId。

我也在用 Knex JS。

知道我在这里做错了什么吗?

提前致谢。

.whereJsonXXX 方法仅适用于 postgresql jsonb 列。

要查询数组列类型,您需要使用数组运算符https://www.postgresql.org/docs/12/functions-array.html

Bet.query()
    .select(
        'id', 
        'status'
    )
    .where('participants_ids', '@>', [userId])
    .range()
    .limit(10)   
    .orderBy('id', 'DESC')
    .throwIfNotFound();

或者如果数组在第一个示例中未正确传递,则可能 .where('participants_ids', '@>', val([userId]).asArray().castTo('integer[]'))