Crudry v2.4.0 Crudry.Query View Source

Generates Ecto Queries.

All functions in this module return an Ecto.Query.

Combining the functions in this module can be very powerful. For example, to do pagination with filter and search:

pagination_params = %{limit: 10, offset: 1, order_by: "id", sorting_order: :desc}
filter_params = %{username: ["username1", "username2"]}
search_params = %{text: "search text", fields: [:username]}

User
|> Crudry.Query.filter(filter_params)
|> Crudry.Query.list(pagination_params)
|> Crudry.Query.search(search_params.text, search_params.fields)
|> Repo.all()

Link to this section Summary

Functions

Applies some restrictions to the query.

Searches for the search_term in the given fields.

Link to this section Functions

Link to this function

filter(initial_query, filters \\ [])

View Source

Filters the query.

Examples

Crudry.Query.filter(MySchema, %{id: 5, name: "John"})
Crudry.Query.filter(MySchema, %{name: ["John", "Doe"]})
Link to this function

list(initial_query, opts \\ [])

View Source

Applies some restrictions to the query.

Expects opts to be a keyword list or a map containing some of these fields:

  • limit: defaults to not limiting
  • offset: defaults to 0
  • sorting_order: defaults to :asc (only works if there is also a order_by specified)
  • order_by: defaults to not ordering
  • custom_query: A function that receives the initial query as argument and returns a custom query. Defaults to initial_query

Examples

Crudry.Query.list(MySchema, [limit: 10])
Crudry.Query.list(MySchema, [limit: 10, offset: 3, sorting_order: :desc, order_by: :value])
Crudry.Query.list(MySchema, %{order_by: "value"})
Crudry.Query.list(MySchema, %{order_by: :value})
Crudry.Query.list(MySchema, %{order_by: ["age", "username"]})
Crudry.Query.list(MySchema, %{order_by: [:age, :username]})
Crudry.Query.list(MySchema, %{order_by: [asc: :age, desc: :username]})
Crudry.Query.list(MySchema, %{order_by: [%{field: "age", order: :asc}, %{field: "username", order: :desc}]})
Crudry.Query.list(MySchema, custom_query: &MySchema.scope_list/1)
Link to this function

search(initial_query, search_term, fields)

View Source

Searches for the search_term in the given fields.

Examples

Crudry.Query.search(MySchema, "John", [:name])