如何打破较小的大型Ecto.Query?

时间:2017-11-20 09:21:37

标签: sql elixir ecto

有没有办法可以在不同的部分分解这个查询并根据需要构建它。我需要不同的部分。

查询工作正常,但复制和粘贴它只是为了改变不同的部分不是很干净的方法。我已经使用#指向我需要重用的块。

 def by_id(user_id, company_id, asset_id) do

        # section 1
        from a in Asset,

        # section 2
        join: acl in AccessList, on: acl.asset_id == a.id, 
        join: c in Company, on: acl.company_id == c.id,
        join: u in User, on: acl.user_id == u.id, 

        # section 3
        where: u.id == ^user_id and c.id == ^company_id

        # section 4 
        and a.id == ^asset_id,
        # section 5
        select: %{ 
            asset_name: a.asset_name, 
            asset_id: a.id,
            inserted_at: a.inserted_at 
            }, 

        # section 6
        group_by: a.id,

        # section 6 
        order_by: a.id

    end  

2 个答案:

答案 0 :(得分:3)

来自Ecto.Query文档:

  

Ecto查询是可组合的。例如,上面的查询实际上可以分为两部分来定义:

# Create a query
query = from u in User, where: u.age > 18
# Extend the query
query = from u in query, select: u.name

那就是说,你可能会:

q1 = from a in Asset

q2 = from a in q1,
     join: acl in AccessList, on: acl.asset_id == a.id, 
     join: c in Company, on: acl.company_id == c.id,
     join: u in User, on: acl.user_id == u.id

答案 1 :(得分:0)

written广泛地介绍了如何编写Ecto查询。当您将此技术与模式匹配相结合时,您可以非常轻松地编写复杂查询。

以下是基于公司查询用户的系统示例。

def list_users(_user, "admin", params) do
  User
  |> filter_by_params(params |>  Map.to_list())
end

def filter_by_params(query, params) do
  Enum.reduce(params, query, fn
    tuple, query ->
      filter_dataset(query, tuple)
  end)
end

def filter_dataset(query, {"company_id", company_id}) do
  query
  |> join(:inner, [u], c in assoc(u, :company))
  |> where([_u, ..., company], company.id == ^company_id)
end

def filter_dataset(query, _no_matching_tuple), do: query