具有nil值的Ecto查询组合

时间:2018-03-20 11:00:27

标签: elixir ecto

我有一个where条件的查询。 where条件中的某些值可以为nil,因此不应查询。我想出了模式匹配和自定义函数,如下所示:

defp add_country(query, nil), do: query
defp add_country(query, country_id), do: from a in query, where: a.country_id == ^country_id
defp add_port(query, nil), do: query
defp add_port(query, port_id), do: from a in query, where: a.port_id == ^port_id

是否有更简单/更清洁的解决方案?我可以在查询中做到吗?也许有选择权?

仅供参考:查询功能:

def list_ads(%{"country_id" => country_id, "port_id" => port_id, "category_id" => category_id}) do
today = Date.utc_today()
query = (from a in Ad,
              where: a.category_id == ^category_id,
              join: c in Contract,
              where: a.contract_id == c.id and
                     c.payment_status == "PAID" and
                     c.expiration >= ^today,
              distinct: [a.user_id, a.plan],
              order_by: a.plan)
        |> add_country(country_id)
        |> add_port(port_id)
Repo.all(query)
end

请不要因“Ad”这个词而气馁。这些纯粹是信息性的,仅在平台上显示,人们来寻找它们。

1 个答案:

答案 0 :(得分:1)

我有一个相当类似的问题。如果保存它的值的变量不是nil,我需要在查询中添加过滤器。我最初在做一堆if。类似的东西:

query = if value do
  from(q in query, where: q.value == ^value)
else
  query
end

这重复了很多次。然后我发现了field/2函数。有了它,我能够动态指定我想要比较的字段。所以我构建了一个函数,让我重用这个逻辑:

defp put_filter(query, _key, nil) do
  query
end

defp put_filter(query, key, value) do
  from(q in query, where: field(q, ^key) == ^value)
end:

用法如下:

query =
  base_query
  |> put_filter(:status, status)
  |> put_filter(:reason, reason)