Relationships

CQL supports four types of associations between models: belongs_to, has_one, has_many, and many_to_many.

belongs_to

A model belongs to another model through a foreign key:

struct Post
  include CQL::ActiveRecord::Model(Int64)
  db_context AppDB, :posts

  getter id : Int64?
  getter title : String
  getter user_id : Int64

  belongs_to :user, User, foreign_key: :user_id
end

# Usage
post = Post.find(1)
author = post.user  # Fetches associated user

has_one

A model has exactly one associated record:

has_many

A model has multiple associated records:

many_to_many

Models related through a join table:

Eager Loading

Prevent N+1 queries by preloading associations:

Nested Eager Loading

Load nested associations:

Association Queries

Query through associations:

Creating Associated Records

Complete Example

Next Steps

Last updated

Was this helpful?