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 Engineer

@ Lemon.io | Remote: Europe, LATAM, Canada, UK, Asia, Oceania

Artificial Intelligence – Bioinformatic Expert

@ University of Texas Medical Branch | Galveston, TX

Lead Developer (AI)

@ Cere Network | San Francisco, US

Research Engineer

@ Allora Labs | Remote

Ecosystem Manager

@ Allora Labs | Remote

Founding AI Engineer, Agents

@ Occam AI | New York