Relations
an5 ORM supports relations between models using foreign keys and declarative schemas.
Sqlserver note:
SQL Server enforces foreign keys via clustered/non-clustered indexes. Relations translate to optimal LEFT JOIN and OUTER APPLY execution plans.
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
Querying Relations in Go
In the generated Go client:
// Query parent user
user, err := db.User.FindUnique(ctx, &an5client.UserWhereUnique{
ID: "user-id",
})
if err != nil {
return err
}
// Fetch related child posts by foreign key
posts, err := db.Post.FindMany(ctx, &an5client.PostWhereInput{
AuthorID: &an5client.StringFilter{Equals: &user.ID},
})
for _, post := range posts {
fmt.Printf("Post: %s\n", post.Title)
}
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