Relation Types Overview
Sonamu supports 4 Relation types:BelongsToOne
N:1 relationship - Many reference one Example: Post β User (multiple posts belong to one user)
OneToOne
1:1 relationship - One references one Example: User β Employee (user and employee info are 1:1
matched)
HasMany
1:N relationship - One owns many Example: User β Posts (one user owns multiple posts)
ManyToMany
N:M relationship - Many-to-many Example: Post β Tag (many-to-many between posts and tags)
BelongsToOne
N:1 relationship - The current Entity belongs to another Entity.Basic Usage
post.entity.json
user_id (integer, not null)
Database structure:
Options
RelationOn Options
Example: nullable and CASCADE
department_idallowsNULL- When department is deleted, employeeβs
department_idis set toNULL
TypeScript Usage
OneToOne
1:1 relationship - Two Entities reference each other exactly once.Basic Usage
OneToOne can be defined in two ways:- hasJoinColumn: true
- hasJoinColumn: false
FK column is created in the current Entity.Generated column:
employee.entity.json
user_id (integer, unique, not null)Database structure:Options
Example: Bidirectional OneToOne
- User can optionally have an Employee (nullable)
- Employee must have a User (not null)
- When User is deleted, Employee is also deleted (CASCADE)
HasMany
1:N relationship - One Entity owns multiple other Entities.Basic Usage
user.entity.json
PostEntity must have auser_idcolumn- Usually defined with
BelongsToOnein reverse onPost
Options
Example: Using fromColumn
TypeScript Usage
HasMany is automatically optimized using the DataLoader pattern. N+1 query problems donβt
occur.
ManyToMany
N:M relationship - Many-to-many relationship implemented through a join table.Basic Usage
post.entity.json
Options
Bidirectional Definition
TypeScript Usage
Custom Join Clause
You can write SQL expressions directly when complex JOIN conditions are needed.Relation Usage Patterns
1. Selecting Relation Fields in Subsets
user: LEFT JOINtags: Separate query via DataLoader
2. Nested Relations
3. Filtering Relations
4. Sorting by Relations
Relation Design Guide
BelongsToOne vs OneToOne
CASCADE vs RESTRICT
nullable Setting
Cautions
Next Steps
Enums
Define and use Enum types
Subset
Type-safe queries with Subsets
Puri Query Builder
Write queries using Relations
Performance
Optimize Relation queries