View Source EctoJuno.Query.Sorting (ecto_juno v0.2.0)
Module for sorting query
Link to this section Summary
Functions
Sorts query by named joint query
Link to this section Functions
@spec sort_query(any(), atom() | list(), map()) :: Ecto.Query.t()
Sorts query
### Parameters
query
: a query you want to sortschema_or_allowed_fields
: either an ecto schema module either a list of which elements are atomsparams
: a map that can havesort_by
,sort_direction
keys with string values
### Usage
alias EctoJuno.Query.Sorting
def sort_users(sort_by, sort_direction) do
params = %{"sort_by" => sort_by, "sort_direction" => sort_direction}
User
|> Sorting.sort_query(User, params)
|> Repo.all()
end
You can also pass sort_by
and sort_direction
as atom keys:
Sorting.sort_query(query, User, %{sort_by: sort_by, sort_direction: sort_direction})
The default sorting is by inserted_at
field with ascending order.
For missing sorting parameters the default values will be used. Same applies and for invalid sorting parameters
Sorts query by named joint query
If query doesn't have provided binding than default sorting will be applied by base query
### Parameters
query
: a query you want to sortschema_or_allowed_fields
: either an ecto schema module either a list of which elements are atomsparams
: a map that can havesort_by
,sort_direction
keys with string valuesbinding
: joint query name
### Usage
alias EctoJuno.Query.Sorting
def sort_users_by_posts(sort_by, sort_direction) do
params = %{"sort_by" => sort_by, "sort_direction" => sort_direction}
User
|> join(:left, [u], p in assoc(u, :posts), as: :posts)
|> Sorting.sort_query(Post, params, :posts)
|> Repo.all()
end