translecto v0.2.1 Translecto.Query
Provides convenient functionality for querying translatable models.
Summary
Macros
Create a query
Macros
Specs
from(term, any, keyword) :: Macro.t
Create a query.
It allows for the standard Ecto.Query.from/2
query syntax and functionality to be used. But adds support for two new expressions locale
and
translate
, aimed at simplifying making translatable queries.
A translatable query is structured as follows:
# Get the english names for all ingredients.
from ingredient in Model.Ingredient,
locale: ^en.id,
translate: name in ingredient.name,
select: name.term
# Get only the ingredients which have english names.
from ingredient in Model.Ingredient,
locale: ^en.id,
must_translate: name in ingredient.name,
select: name.term
# Get the english and french names for all ingredients.
from ingredient in Model.Ingredient,
locales: ^[en.id, fr.id],
translate: name in ingredient.name,
select: name.term
A translatable query requires a locale to be set using the :locale
keyword. This value should be
the locale value that will be matched in the translation model’s for :locale_id
field. Alternatively
a list of locales can be matched against using the keywork :locales
, where a list of locale values
is provided.
The :translate
keyword is used to create access to any translatable terms, if those terms are not
available it will return null instead. While :must_translate
is an alternative keyword that enforces
a translation exists. These take the form of an in
expression where the left argument is the named
reference to that translation, and the right argument is the translatable field (field marked as
Translecto.Schema.Translatable.translatable/3
.
After using translate the translatable term(s) for that field are now available throughout the query, in the given locale specified.
# Get the ingredient whose english name matches "orange"
from ingredient in Model.Ingredient,
locale: ^en.id,
translate: name in ingredient.name, where: name.term == "orange",
select: ingredient
Multiple translates can be used together in the same expression to translate as many fields of the translatable fields as needed.