Elixir 仅当存在参数时,如何在EXTO中定义联接?
我正在尝试创建一个函数来执行一些动态查询。有一种情况下,我希望添加与另一个表的联接,但只有在Elixir 仅当存在参数时,如何在EXTO中定义联接?,elixir,ecto,Elixir,Ecto,我正在尝试创建一个函数来执行一些动态查询。有一种情况下,我希望添加与另一个表的联接,但只有在opts def list_fields(opts) do query = from f in Field, select: %{ id: f.id, type: f.type, value: f.value } with query <- by_type(opts[:type], query),
opts
def list_fields(opts) do
query =
from f in Field,
select: %{
id: f.id,
type: f.type,
value: f.value
}
with query <- by_type(opts[:type], query),
query <- by_status(opts[:status], query) do
Repo.all(query)
end
end
但是,状态存储在不同的表中,我不想向其中添加联接,除非我必须避免结果重复
具有联接的查询如下所示:
query =
from f in Field,
left_join: d in Data, on: d.field_id = f.id
select: %{
...
只有当:status
出现在opts
中时,我如何添加此左连接?使用
{{,查询}=
使用{status,query}when not is_nil(status),我明白了,但是如果status
不是nil
,这如何帮助我将连接添加到查询中?你有整个do
块来返回你想要的任何查询。哦,我明白了,所以我无论如何都需要有两个版本的查询?我在想办法避免那样。谢谢你的帮助:)我不明白。您将有1个查询。查询是可组合的。使用With
您将编写更复杂的查询。我知道这可能是一个愚蠢的问题,但我正在一边学习长生不老药,我知道这不是最好的方法。我想知道的是,在查询的left\u join
中,我应该在哪一点添加
query =
from f in Field,
left_join: d in Data, on: d.field_id = f.id
select: %{
...
{_, query} =
with {status, query} when not is_nil(status) <-
{opts[:status], by_type(opts[:type], query)},
do: {:ok, by_status(opts[:status], query)}
Repo.all(query)