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 仅当存在参数时,如何在EXTO中定义联接?_Elixir_Ecto - Fatal编程技术网

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)