Skip to content

Eloquex Relationships

David Ciulla edited this page Nov 7, 2026 · 2 revisions

Eloquex: Relationships

Eloquex supports four relationship types — has_one, has_many, belongs_to, and belongs_to_many — implemented in Laravex.Eloquex.Relation. Relationships are declared in the model's relations/0 callback and loaded eagerly with with/2 or lazily with load/2.

Defining Relationships

Declare relationships by returning a list from relations/0:

defmodule App.Models.User do
  use Laravex.Eloquex.Model, table: "users"

  defstruct [:id, :name, :email, :created_at, :updated_at]

  def relations do
    [
      has_many(:posts, App.Models.Post),
      has_one(:profile, App.Models.Profile),
      belongs_to_many(:roles, App.Models.Role)
    ]
  end
end

defmodule App.Models.Post do
  use Laravex.Eloquex.Model, table: "posts"

  defstruct [:id, :user_id, :title, :body, :created_at, :updated_at]

  def relations do
    [
      belongs_to(:user, App.Models.User),
      has_many(:comments, App.Models.Comment)
    ]
  end
end

Foreign keys follow Laravel conventions and are computed automatically:

Relationship Default foreign key
has_many(name, Related) <owner_snake>_id on the related table
has_one(name, Related) <owner_snake>_id on the related table
belongs_to(name, Related) <name>_id on the owner table
belongs_to_many(name, Related) Pivot table: alphabetically-sorted <a>_<b>, keys <owner>_id / <related>_id

Override any of these by passing explicit arguments:

has_many(:posts, App.Models.Post, "author_id")
belongs_to(:author, App.Models.User, "author_id")
belongs_to_many(:tags, App.Models.Tag, "post_tag", "post_id", "tag_id")

Eager Loading

Load relations for a list of models with a single batched query per relation (N+1 free):

posts = App.Models.Post.all()

posts = App.Models.Post.with(posts, [:user, :comments])
# Single query per relation — not N+1

Multiple relations:

users = App.Models.User.with(users, [:posts, :profile, :roles])

Lazy Loading

Load a relation for a single model:

post = App.Models.Post.find(1)
post = App.Models.Post.load(post, :user)

user = post |> App.Models.Post.association(:user) |> Laravex.Eloquex.Relation.BelongsTo.get()

Counting Relations

Attach a <relation>_count to each model without loading the full relation:

users = App.Models.User.with_count(users, [:posts])

# Access the count
user.posts_count  # note: stored via Process, accessed as a loaded value

Accessing Loaded Relations

After with/2 or load/2, check whether a relation was loaded and retrieve it:

if Laravex.Database.Model.relation_loaded?(post, :user) do
  user = Laravex.Database.Model.get_relation(post, :user)
end

This is primarily used by Eloquex-Resources via when_loaded/2.

has_many

# Using the relation struct directly
rel = App.Models.Post.association(post, :comments)
comments = Laravex.Eloquex.Relation.HasMany.get(rel)

# Create a child via the relation (automatically sets foreign key)
comment = Laravex.Eloquex.Relation.HasMany.create(rel, %{"body" => "Great post!"})

has_one

rel = App.Models.User.association(user, :profile)
profile = Laravex.Eloquex.Relation.HasOne.get(rel)   # returns first match or nil

belongs_to

rel = App.Models.Post.association(post, :user)
user = Laravex.Eloquex.Relation.BelongsTo.get(rel)

# Associate / dissociate (mutates the owner struct, does not save)
post = Laravex.Eloquex.Relation.BelongsTo.associate(rel, new_user)
post = Laravex.Eloquex.Relation.BelongsTo.dissociate(rel)   # sets FK to nil

belongs_to_many

rel = App.Models.User.association(user, :roles)

# Get all related models
roles = Laravex.Eloquex.Relation.BelongsToMany.get(rel)

# Attach — inserts rows into the pivot table
Laravex.Eloquex.Relation.BelongsToMany.attach(rel, [1, 2, 3])

# With extra pivot attributes
Laravex.Eloquex.Relation.BelongsToMany.attach(rel, [1], %{"expires_at" => "2027-01-01"})

# Detach specific IDs
Laravex.Eloquex.Relation.BelongsToMany.detach(rel, [2, 3])

# Detach all
Laravex.Eloquex.Relation.BelongsToMany.detach(rel, :all)

# Sync — detach all then attach the given IDs
Laravex.Eloquex.Relation.BelongsToMany.sync(rel, [1, 4, 5])

# Sync without detaching existing IDs (Laravel `syncWithoutDetaching`)
Laravex.Eloquex.Relation.BelongsToMany.sync_without_detaching(rel, [3, 6])

# Toggle — attach missing IDs, detach existing IDs
Laravex.Eloquex.Relation.BelongsToMany.toggle(rel, [2, 5])

# Update a pivot row's extra attributes for a specific related ID
Laravex.Eloquex.Relation.BelongsToMany.update_existing_pivot(
  rel, 2, %{"expires_at" => "2028-01-01"}
)

The pivot table is populated with created_at and updated_at timestamps automatically.

Polymorphic Relationships

Polymorphic relations let a model belong to more than one other model on a single association using {name}_type / {name}_id column pairs.

morph_many / morph_one

defmodule App.Models.Post do
  use Laravex.Eloquex.Model, table: "posts"

  def relations do
    [
      # a Post can have many Comments (morphable)
      morph_many(:comments, App.Models.Comment, "commentable")
    ]
  end
end

defmodule App.Models.Video do
  use Laravex.Eloquex.Model, table: "videos"

  def relations do
    [morph_one(:thumbnail, App.Models.Image, "imageable")]
  end
end

The related table must have commentable_type TEXT and commentable_id INTEGER columns (see Migrations#Morph Columns).

morph_to

defmodule App.Models.Comment do
  use Laravex.Eloquex.Model, table: "comments"

  def relations do
    [
      # commentable_type + commentable_id resolve the parent
      morph_to(:commentable)
    ]
  end
end

morph_to resolves the parent model by looking up commentable_type in the morph map (database.morph_map config) or by trying App.Models.<CamelType>.

morph_to_many

A polymorphic many-to-many (e.g., tags on posts and videos):

morph_to_many(:tags, App.Models.Tag, "taggables", "taggable", "tag_id")

The pivot table (taggables) needs taggable_type, taggable_id, and tag_id columns.

Morph Map

Register string aliases to decouple type strings from module names:

# config/database.exs
%{
  "morph_map" => %{
    "post"    => App.Models.Post,
    "video"   => App.Models.Video
  }
}

where_has / or_where_has / has / where_doesnt_have / or_where_doesnt_have / doesnt_have

Filter owners by the existence of a relation (uses a correlated EXISTS subquery):

# Users who have at least one post
users_with_posts = App.Models.User.where_has("posts")

# Alias: has/1 is identical to where_has/1
users_with_posts = App.Models.User.has("posts")

# Users who have a published post
users =
  App.Models.User.query()
  |> App.Models.User.where_has("posts", fn q ->
    Laravex.Database.Query.where(q, "published", 1)
  end)
  |> Laravex.Database.Query.get()
  |> Enum.map(&App.Models.User.from_row/1)

# OR version — append with OR EXISTS
users =
  App.Models.User.query()
  |> App.Models.User.where_has("posts")
  |> App.Models.User.or_where_has("comments")
  |> Laravex.Database.Query.get()

# Users without any posts
App.Models.User.where_doesnt_have("posts")

# Alias: doesnt_have/1
App.Models.User.doesnt_have("posts")

# OR NOT EXISTS
App.Models.User.query()
|> App.Models.User.where_doesnt_have("posts")
|> App.Models.User.or_where_doesnt_have("comments")
|> Laravex.Database.Query.get()

load_count, load_missing, and without

# Attach a *_count field without loading the full relation
[user] = App.Models.User.load_count(user, [:posts, :comments])
# user.posts_count / user.comments_count available via get_relation/2

# Eager-load only relations not already loaded
posts = App.Models.Post.load_missing(posts, [:user, :comments])

# Unload relations from a model (removes from process dictionary)
post = App.Models.Post.without(post, [:comments])

Touching Parent Timestamps

Define a touches/0 callback to automatically update a parent's updated_at when the child is saved:

defmodule App.Models.Comment do
  use Laravex.Eloquex.Model, table: "comments"

  def relations do
    [belongs_to(:post, App.Models.Post)]
  end

  def touches, do: [:post]
end

See Also

Clone this wiki locally