Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Elixir 具有零值的外部查询组合_Elixir_Ecto - Fatal编程技术网

Elixir 具有零值的外部查询组合

Elixir 具有零值的外部查询组合,elixir,ecto,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

我有一个带有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
query =
  base_query
  |> put_filter(:status, status)
  |> put_filter(:reason, reason)
是否有更简单/更清洁的解决方案?我可以在查询本身中这样做吗?也许有选择

仅供参考:查询功能:

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

请不要因为里面的“广告”这个词而气馁。这些都是纯粹的信息,只显示在平台上,人们来寻找它们

我也有类似的问题。如果保存其值的变量不是
nil
,我需要在查询中添加过滤器。我最初做了一系列的假设。比如:

query = if value do
  from(q in query, where: q.value == ^value)
else
  query
end
这已经重复了很多次。然后我发现了这个函数。有了它,我可以动态地指定要比较的字段。所以我构建了一个函数,让我可以重用这个逻辑:

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:
用法如下所示:

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
query =
  base_query
  |> put_filter(:status, status)
  |> put_filter(:reason, reason)

也许这个功能可以进入外胚层<代码>放入过滤器,除非为零/3。这是模式匹配的一般方法。我喜欢,泰。我很高兴能帮上忙。我会考虑打开一个拉请求到ECTO对此: