如何概括此Ecto / Elixir函数?

时间:2019-02-04 09:55:23

标签: elixir phoenix-framework ecto

我有以下内容,如果存在platform,它将WHERE语句应用于ecto查询。

  defp maybe_platform(queryable, false), do: queryable
  defp maybe_platform(queryable, platform) do
      queryable
      |> where([c], c.platform == ^platform)
  end

如何对任何变量(而不只是platform)进行泛化? (这是我在苦苦挣扎的c.platform位)

3 个答案:

答案 0 :(得分:2)

您需要使用Ecto field https://hexdocs.pm/ecto/Ecto.Query.API.html#field/2

您的功能看起来像这样

defp maybe_field(queryable, field_name, field_value) do
    queryable
    |> where([c], field(c, ^field_name) == ^field_value)
end

然后

(from m in MyModel)
|> maybe_field(:platform, "platform_name_or_variable")
|> maybe_field(:another_field, "some value")
|> maybe_field(:is_platform_enabled, true)
|> Repo.all

答案 1 :(得分:0)

您可以使用关键字作为过滤器。看看Ecto.Query#where/3

from(c in City, where: c.country == "Sweden")
from(c in City, where: [country: "Sweden"])

答案 2 :(得分:0)

Ecto.Query.where/3接受关键字列表作为过滤器。 Elixir关键字列表只是每个两个元素的元组的Erlang列表的包装。话虽如此,但这样可以做到:

defp maybe_where(queryable, _param, false), do: queryable
defp maybe_where(queryable, param, value) do
  filters = [{param, value}]
  where(queryable, ^filters)
end