【问题标题】:Ecto query to grab all values that satisfy all values in array_aggregator not just any?Ecto 查询以获取满足 array_aggregator 中所有值的所有值,而不仅仅是任何值?
【发布时间】:2019-05-22 16:11:38
【问题描述】:

想知道是否有人可以帮助我解决数组聚合器问题

我有一个查询,它使用连接表进行连接,然后过滤掉给定数组中的所有值,并过滤掉另一个数组中的值。

代码如下:

      Product
      |> join(:inner, [j], jt in "job_tech", on: j.id == jt.product_id)
      |> join(:inner, [j, jt], t in Tech, on: jt.ingredient_id == t.id)
      |> group_by([j], j.id)
      |> having_good_ingredients(good_ingredients)
      |> not_having_bad_ingredients(bad_ingredients)

having_good_ingredients 看起来像这样:

def having_good_ingredients(query, good_ingredients) do
    if Enum.count(good_ingredients) > 0 do
      query
      |> having(fragment("array_agg(t2.name) && (?)::varchar[]", ^good_ingredients))
    else
      query
    end
  end

这可行,但它会抓取满足 good_stacks 数组中任何值的所有值,我希望它们仅在所有堆栈都工作时才满足 即,如果我的数组中有 [A, C],我想返回具有 A AND C 的值,而不仅仅是 A 而不仅仅是 C。

有人有什么想法吗?

【问题讨论】:

    标签: postgresql elixir ecto array-agg


    【解决方案1】:

    我相信您想使用@> 运算符,而不是重叠&& 运算符:

    having(fragment("array_agg(t2.name) @> (?)::varchar[]", ^good_ingredients))
    

    参考:https://www.postgresql.org/docs/current/functions-array.html#ARRAY-OPERATORS-TABLE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      相关资源
      最近更新 更多