受到这个伟大答案(How to simplify `case` iteraction when the code is almost the same)的启发,我认为可能有一种方法可以做类似于此查询的操作来动态操作这些字段:
u.date, u.title, u.text
- u.date_pt, u.title_pt, u.text_pt
- u.date_es, u.title_es, u.text_es
-...
在此查询中:
def search(query, search_term, locale) do
language =
case locale do
"pt" ->
"Portuguese"
"es" ->
"Spanish"
"fr" ->
"Spanish"
"de" ->
"German"
_ ->
"English"
end
f = if locale in ~w(en pt es fr de), do: :"u.date_#{locale}, u.title_#{locale}, u.text_#{locale}", else: :u.date, u.title, u.text # This is WRONG, just to illustrate what's intended
(from u in query,
where: fragment("(to_tsvector(?, unaccent(?)) || to_tsvector(?, unaccent(?)) || to_tsvector(coalesce(?, unaccent(?)))) @@ plainto_tsquery(?, unaccent(?))",
^language, u.date, ^language, u.title, ^language, u.text, ^language, ^search_term),
order_by: fragment("ts_rank((to_tsvector(?, ?) || to_tsvector(?, ?) || to_tsvector(coalesce(?, ?))), plainto_tsquery(?, ?)) DESC",
^language, u.date, ^language, u.title, ^language, u.text, ^language, ^search_term))
|> Repo.all()
end
是吗?
答案 0 :(得分:2)
是的,您可以在Ecto查询中使用field/2
。我这样做:
suffix = if locale in ~w(pt es fr de), do: "_#{locale}", else: ""
然后,在查询中,而不是
u.date
做的:
field(u, ^:"date#{suffix}")
同样,u.title
变为field(u, ^:"title#{suffix}")
,依此类推。