Feb. 19, 2024, 6:46 p.m. | Artur Plysiuk

DEV Community dev.to

There is already an existing article in Ecto docs about dynamic queries https://hexdocs.pm/ecto/dynamic-queries.html so you might think why another article is needed.


Indeed, the article from docs contains a solid foundation. However, I suggest organizing the final code differently. Let's examine the code:



def filter(params) do
Post
|> join(:inner, [p], assoc(p, :authors), as: :authors)
|> order_by(^filter_order_by(params["order_by"]))
|> where(^filter_where(params))
end

def filter_order_by("published_at_desc"),
do: [desc: dynamic([p], p.published_at)]

def filter_order_by("published_at"),
do: dynamic([p], p.published_at)

def filter_order_by("author_name_desc"),
do: [desc: dynamic([authors: a], a.name)]

def filter_order_by("author_name"),
do: …

article authors code dynamic elixir filter foundation indeed join params solid

Data Architect

@ University of Texas at Austin | Austin, TX

Data ETL Engineer

@ University of Texas at Austin | Austin, TX

Lead GNSS Data Scientist

@ Lurra Systems | Melbourne

Senior Machine Learning Engineer (MLOps)

@ Promaton | Remote, Europe

Principal Data Engineering Manager

@ Microsoft | Redmond, Washington, United States

Machine Learning Engineer

@ Apple | San Diego, California, United States