Relations
Has_many
One to One
belongs_to indicates a one-to-one or many-to-one association with another schema. Defines a foreign key that is the primary key of the listed table.
belongs_to(has the id in its table) =>has_onehas their id in their belongs_to tableThe other schema often has a
has_oneor ahas_manyfield with same fields, but reverse association. (Both the has macros don't change DB, just allow access)
schema "organization_subscriptions" do
belongs_to :organization, ReactPhoenix.Organizations.Organization, type: :string
# subscriptions has organization_id schema "organizations" do
has_one :subscription, ReactPhoenix.Organizations.Subscription
#nothing in table organizationsUsage
# Can Preload the belongs_to post on the comment
[comment] = Repo.all(from(c in Comment, where: c.id == 42, preload: :post))
comment.post #=> %Post{...}
#Or the post
[post] = Repo.all(from(p in Post, where: p.id == 42, preload: :comments))
post.comments #=> [%Comment{...}, ...]Updating from parent
You could pass in %{id: 1, child: [1]}
:on_replace- The action taken on associations when the record is replaced when casting or manipulating parent changeset. May be:raise(default),:mark_as_invalid,:nilify,:update, or:delete. SeeEcto.Changeset's section on related data for more info.
Create/Update Relations
This function should be used when working with the entire association at once (and not a single element of a many-style association) and receiving data external to the application.
It compares each of param to preloaded
No id or id not in db => insert
if id and in db => update
If no id, but id in db => delete/on_replace
In Creation
In Update
In Get
Example Schema
Last updated