Ecto.Associations behaviour
Documents the functions required for associations to implement in order to work with Ecto query mechanism.
This module contains documentation for those interested in
understanding how Ecto associations work internally. If you are
interested in an overview about associations in Ecto, you should
look into the documentation for Ecto
and Ecto.Model.Schema
modules.
Associations
Associations work in Ecto via behaviours. Anyone can add new associations to Ecto as long as they implement the callbacks specified in this module.
Note though that, since the associations API is in development, existing callbacks signature and new callbacks can be added in upcoming Ecto releases.
Summary↑
association_from_model!(model, assoc) | Retrieves the association from the given model |
association_key(module, suffix) | Returns the association key for the given module with the given prefix |
underscore(arg1) |
Types ↑
t :: %module{cardinality: :one | :many, field: atom, owner_key: atom}
Functions
Retrieves the association from the given model.
Returns the association key for the given module with the given prefix.
Examples
iex> Ecto.Associations.association_key(Hello.World, :id)
:world_id
iex> Ecto.Associations.association_key(Hello.HTTP, :id)
:http_id
iex> Ecto.Associations.association_key(Hello.HTTPServer, :id)
:http_server_id
Callbacks
Specs:
- assoc_query(t, values :: [term]) :: Ecto.Query.t
Returns the association query.
This callback receives the association struct and it must return a query that retrieves all associated objects with the given values for the owner key.
This callback is used by Ecto.Model.assoc/2
.
Specs:
- build(t, Ecto.Model.t) :: Ecto.Model.t
Builds a model for the given association.
The struct to build from is given as argument in case default values should be set in the struct.
Invoked by Ecto.Model.build/2
.
Specs:
- joins_query(t) :: Ecto.Query.t
Returns an association join query.
This callback receives the association struct and it must return a query that retrieves all associated objects using joins up to the owner association.
For example, a has_many :comments
inside a Post
module would
return:
from c in Comment, join: p in Post, on: c.post_id == p.id
Note all the logic must be expressed inside joins, as fields like
where
and order_by
won't be used by the caller.
This callback is invoked when join: assoc(p, :comments)
is used
inside queries.
Specs:
Builds the association struct.
The struct must be defined in the module that implements the callback and it must contain at least the following keys:
:cardinality
- tells if the association is one to one or one/many to many:field
- tells the field in the owner struct where the association should be stored:owner_key
- the key in the owner with the association value:assoc_key
- the key in the association with the association value