首页 > 解决方案 > Slick-pg:如何使用 arrayElementsText 和重叠运算符“?|”?

问题描述

我正在尝试使用slick / slick-pg在scala中编写以下查询,但我对 slick 没有太多经验并且无法弄清楚如何:

SELECT * 
FROM attributes a 
WHERE a.other_id = 10 
      and ARRAY(SELECT jsonb_array_elements_text(a.value->'value'))
          && array['1','30','205'];

这是属性表的简化版本,其中value字段是jsonb

class Attributes(tag: Tag) extends Table[Attribute](tag, "ship_attributes") {
    def id = column[Int]("id")
    def other_id = column[Int]("other_id")
    def value = column[Json]("value")

    def * = (id, other_id, value) <> (Attribute.tupled, Attribute.unapply)

}

样本数据:

|  id  |  other_id  |  value                                    |
|:-----|:-----------|:------------------------------------------|
|  1   |  10        | {"type": "IdList", "value": [1, 21]}      | 
|  2   |  10        | {"type": "IdList", "value": [5, 30]}      | 
|  3   |  10        | {"type": "IdList", "value": [7, 36]}      | 

这是我当前的查询:

attributes
    .filter(_.other_id = 10)
    .filter { a => 
        val innerQuery = attributes.map { _ => 
            a.+>"value".arrayElementsText
        }.to[List]
        innerQuery @& List("1", "30", "205").bind
    }

但它抱怨.to[List]转换。

我试图创建一个SimpleFunction.unary[X, List[String]]("ARRAY"),但我不知道如何传递innerQuery给它(innerQueryis Query[Rep[String], String, Seq])。

任何想法都非常感谢。

更新 1

虽然我无法弄清楚这一点,但我更改了应用程序以将 json 字段作为字符串列表而不是整数保存在数据库中,以便能够执行此简单查询:

attributes
    .filter(_.other_id = 10)
    .filter(_.+>"value" ?| List("1", "30", "205").bind)


|  id  |  other_id  |  value                                    |
|:-----|:-----------|:------------------------------------------|
|  1   |  10        | {"type": "IdList", "value": ["1", "21"]}  | 
|  2   |  10        | {"type": "IdList", "value": ["5", "30"]}  | 
|  3   |  10        | {"type": "IdList", "value": ["7", "36"]}  | 

标签: postgresqlscalaslickslick-pg

解决方案


推荐阅读