为基于列表的 Ecto 查询重复一个 where 子句语句

Repeat a where clause statement for an Ecto query based on a list

我正在尝试使用 Ecto/postgres 创建搜索查询。这是我查询的第一部分:

query = from l in Log,
  join: u in assoc(l, :user),
  where: u.id == ^current_user.id,
  select: l

用户可以在文本框中输入任意数量的术语(以白色 space 分隔),然后这些术语用于过滤结果集。我正在使用 String.split 将原始字符串转换为一组附加到查询的 where 子句(AND'd 在一起):

search_term
|> String.split()
|> Enum.map( fn(term) ->
  query = from l in query,
    where: fragment("comment ~* ?", ^term)
end)

除了这条语句没有任何作用。我假设 query 赋值只存在于函数的范围内。我的头脑被命令式思维所笼罩。我如何以实用的方式实现这一目标?

I'm assuming that the query assignment only lives within the scope of the function.

是的,完全正确。

你应该为此使用Enum.reduce,并将原始查询作为累加器的初始值传递:

search_term
|> String.split()
|> Enum.reduce(query, fn(term, query) ->
  from l in query, where: fragment("comment ~* ?", ^term)
end)