gpt4 book ai didi

arrays - Ecto 查询 Postgres JSON 数组的值

转载 作者:行者123 更新时间:2023-11-29 13:19:58 25 4
gpt4 key购买 nike

我有以下架构,它是一个用于帖子表的 JSONB 字段,它将保存所有使用的标签。

schema "posts" do
...
field :tags, {:array, :string}
...
end

它有一个“标签”数组作为“字符串”。我想在此数组中搜索字符串值。我试过:

def search_by_tag(query, tag) do
from p in query,
where: fragment("? @> ?", p.tags, ^tag)
end

但没有成功,我正在寻找一种搜索 JSONB 数组并找到值(如果值存在)的方法。此外,它应该使查询函数与非 JSONB 查询兼容,以便继续执行以下操作:

Blog.Post |> Blog.Post.search_by_tag("tag1") |> Blog.User.active()

最佳答案

@> 函数期望第二个操作数是数组,所以:

def search_by_tag(query, tag) do
tags = [tag]
from p in query,
where: fragment("? @> ?", p.tags, ^tags)
end

ecto 语法本身也支持这种情况:

def search_by_tag(query, tag) do
from p in query,
where: tag in p.tags
end

同样对于可组合查询Blog.Post.search_by_tag("tag1") |> Blog.User.active(),您可能会考虑使用"pipe-based syntax"

关于arrays - Ecto 查询 Postgres JSON 数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43740726/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com