Skip to main content
Relations define how entities are connected to each other. ChameleonDB supports one-to-many and many-to-one relationships using the via keyword.

Relation Types

ChameleonDB supports two primary relation patterns:

One-to-Many (Has Many)

Defines a collection relationship where one entity has multiple related entities:
Syntax:

Many-to-One (Belongs To)

Defines a single relationship where one entity belongs to another:
Syntax:

The via Keyword

The via keyword specifies the foreign key field in the related entity:
The via keyword is only used for one-to-many relations (arrays). Many-to-one relations infer the foreign key automatically.

Bidirectional Relations

Most relationships are bidirectional - defined from both sides:

Foreign Key Fields

Foreign key fields must be explicitly declared:
The foreign key field (user_id) must match the type of the target entity’s primary key.

Nested Relations

Relations can be traversed through multiple levels:
Querying nested relations:

Self-Referential Relations

Entities can reference themselves:

Complete Example

Here’s a complete e-commerce schema demonstrating all relation patterns:

Relation Validation

ChameleonDB validates relations at compile time:
Target Exists - The target entity must be defined in the schema
Foreign Key Type Match - Foreign key type must match the target’s primary key type
Foreign Key Exists - For via relations, the foreign key field must exist in the target entity
No Circular Ownership - Entities cannot form circular ownership dependencies

Querying Relations

Relations are traversed using the query API:

Eager Loading

Load related entities to avoid N+1 queries:

Nested Includes

Multiple Relations

Best Practices

Name foreign keys consistently - Use {entity}_id pattern (e.g., user_id, order_id)
Define bidirectional relations - Define both sides for easier querying
Use meaningful relation names - Choose names that reflect the domain relationship
Use eager loading - Always use Include() to avoid N+1 query problems

Common Patterns

Parent-Child

Author-Content

Order-Line Items

Limitations

Many-to-many not yet supported - Use a join entity pattern instead:

Next Steps

Field Types

Learn about field types for foreign keys

Constraints

Add validation to relations