Relations
an5 ORM supports relations between models using foreign keys and declarative schemas.
Googlesheets note: The Google Sheets adapter resolves relations by cross-referencing matching ID columns across individual sheet tabs in memory.
Defining Relations
One-to-Many
model User {
id NVARCHAR(1000) @id @default(uuid())
email NVARCHAR(255) @unique
posts Post[] // One user has many posts
}
model Post {
id NVARCHAR(1000) @id @default(uuid())
title NVARCHAR(255)
content TEXT
published BOOLEAN @default(false)
authorId NVARCHAR(1000)
createdAt DATETIME @default(now())
author User @relation(fields: [authorId], references: [id])
}
One-to-One
model User {
id NVARCHAR(1000) @id @default(uuid())
email NVARCHAR(255) @unique
profile Profile?
}
model Profile {
id NVARCHAR(1000) @id @default(uuid())
bio TEXT
userId NVARCHAR(1000) @unique
user User @relation(fields: [userId], references: [id])
}
Many-to-Many
Implicit many-to-many join tables are not generated automatically. Model many-to-many as an explicit join model with two foreign keys:
model PostTag {
id NVARCHAR(1000) @id @default(uuid())
postId NVARCHAR(1000)
tagId NVARCHAR(1000)
post Post @relation(fields: [postId], references: [id])
tag Tag @relation(fields: [tagId], references: [id])
@@map("post_tags")
}
Querying Relations
Include Relations in Swift
import An5Client
var byId = An5Orm.UserWhere()
byId.id = An5Orm.StringFilter.`is`(userId)
let user = try db.user.findFirst(Query(
filter: byId.build(),
include: ["posts": true]
))
Query carries the whole call, and the value under the relation name is true or a
dictionary of the same options:
let user = try db.user.findFirst(Query(
filter: byId.build(),
include: ["posts": [
"where": ["title": ["contains": "AN5"]],
"orderBy": ["id": "desc"],
"take": 5,
"select": ["id", "title"],
]]
))
Relation Filters
The some / every / none shorthand is the TypeScript adapter’s. The Swift SQL
builder never reads it, and a key it cannot parse lands in an empty WHERE, which
matches every row instead of failing — so filter from the child side:
let posts = try db.post.findMany(Query(
filter: ["authorId": ["equals": userId]]
))
Nested Create & Connect
One row per call, so a nested create is two calls in one transaction:
let post = try db.transaction {
let author = try db.user.create(User(email: "john@example.com"))
return try db.post.create(Post(title: "Post 1", authorId: author.id))
}
Cascade Operations
Configure cascade delete behavior in your .an5 schema using @cascade:
model User {
id NVARCHAR(1000) @id @default(uuid())
posts Post[] @cascade
@@map("users")
}
model Post {
id NVARCHAR(1000) @id @default(uuid())
authorId NVARCHAR(1000)
author User @relation(fields: [authorId], references: [id])
@@map("posts")
}
Next Steps
- Advanced Queries - Complex filtering, aggregation and raw SQL
- Transactions - Atomic multi-table updates