Loading relations
Load a relation with Include
Include loads a []T relation, and IncludeOne loads a *T one. Each adds one query however many parents there are.
users, err := db.Users.
OrderBy(&Users.Name).
Include(&Users.Posts).
All(ctx)
// SELECT ... FROM "users" ORDER BY "users"."name"
// SELECT ... FROM "posts" WHERE "posts"."user_id" IN ($1, $2, $3)
fmt.Println(users[0].Posts[0].Title)
posts, err := db.Posts.
IncludeOne(&Posts.User).
All(ctx)
// SELECT ... FROM "posts"
// SELECT ... FROM "users" WHERE "users"."id" IN ($1, $2)
fmt.Println(posts[0].User.Name)
Include works with All, First, Single, Find, and Chunk. Each streams rows, so it can't batch a second query and returns ant.ErrIncludeInEach. When no parent comes back, the second query doesn't run. Posts with the same author share one *User.
Call it once per relation to load several.
Tell "not loaded" from "none"
user, err := db.Users.Find(ctx, id)
fmt.Println(user.Posts == nil) // true: not loaded
loaded, err := db.Users.Include(&Users.Posts).Find(ctx, id)
fmt.Println(loaded.Posts != nil) // true: loaded, and maybe empty
Filter and order what loads
The optional function shapes the related query with the usual query methods.
users, err := db.Users.
Include(&Users.Posts, func(q *ant.Query[Post]) *ant.Query[Post] {
return q.Where(ant.Eq(&Posts.Published, true)).OrderByDesc(&Posts.CreatedAt)
}).
All(ctx)
// SELECT ... FROM "posts"
// WHERE "posts"."published" = $1 AND "posts"."user_id" IN ($2, ...)
// ORDER BY "posts"."created_at" DESC
The latest three of each
Limit and Offset apply per parent: each user gets their three newest posts. That holds through a join table too, for a many-to-many or a HasManyThrough relation.
users, err := db.Users.
Include(&Users.Posts, func(q *ant.Query[Post]) *ant.Query[Post] {
return q.OrderByDesc(&Posts.CreatedAt).Limit(3)
}).
All(ctx)
// SELECT * FROM (
// SELECT ..., ROW_NUMBER() OVER (PARTITION BY "posts"."user_id" ORDER BY "posts"."created_at" DESC) AS "ant_row"
// FROM "posts" WHERE "posts"."user_id" IN ($1, ...)
// ) AS "ant_partition"
// WHERE "ant_partition"."ant_row" > $2 AND "ant_partition"."ant_row" <= $3
// ORDER BY "ant_partition"."ant_row"
Pick columns
Column picks columns. The foreign key is always kept so ant can match rows to parents. The same holds the other way: a parent query with Column or Omit still reads the key its includes match by.
users, err := db.Users.
Include(&Users.Posts, func(q *ant.Query[Post]) *ant.Query[Post] {
return q.Column(&Posts.Title)
}).
All(ctx)
// SELECT "posts"."title", "posts"."user_id" FROM "posts" WHERE "posts"."user_id" IN ($1, ...)
IncludeOne takes a shape too. A filter that excludes the parent leaves the field nil.
Load several levels
Include inside the function loads the next level, down or up. Each level is one query.
users, err := db.Users.
Include(&Users.Posts, func(q *ant.Query[Post]) *ant.Query[Post] {
return q.Include(&Posts.Comments)
}).
All(ctx)
// SELECT ... FROM "users"
// SELECT ... FROM "posts" WHERE "posts"."user_id" IN ($1, ...)
// SELECT ... FROM "comments" WHERE "comments"."post_id" IN ($1, $2, ...)
Load a parent in the same statement
IncludeJoined reads a parent through a LEFT JOIN, in one query instead of the two IncludeOne runs. A missing parent stays nil and the row is kept.
posts, err := db.Posts.IncludeJoined(&Posts.User).OrderBy(&Posts.Title).All(ctx)
// SELECT "posts"."id", ..., "ant_joined0"."id", "ant_joined0"."name", ...
// FROM "posts" LEFT JOIN "users" AS "ant_joined0" ON "posts"."user_id" = "ant_joined0"."id"
// ORDER BY "posts"."title"
To filter or order on the parent, use a join. IncludeJoined can't load where a query is not read as rows of its model, so Each, set operations, From, FromCTE, Recursive and JoinSub refuse it with ant.ErrIncludeInEach or ant.ErrIncludeInSubquery, as they refuse Include.
Include and tracked entities
On a session, Include reads each parent's relation afresh, as Load does, and replaces what the parent held. The replaced elements are released, so the slice shows what a save would write.
Unsaved changes to a relation are replaced by the query. Save first:
session := ant.Session(db)
alice, err := session.Users.Include(&Users.Posts).Find(ctx, id)
alice.Posts = append(alice.Posts, Post{Title: "Draft"})
err = session.SaveChanges(ctx) // write the new post first
users, err := session.Users.Include(&Users.Posts).All(ctx) // then read
Without the save, the second query replaces alice.Posts with the stored rows and drops the draft. An entity that was inserted with its relations starts out tracked as if loaded with them. See changing relations.
Include sets each parent's relation in one write, so a parent never shows half its rows. A parent that appears twice is filled once.
Load relations later
Load fills relations on entities you already have, in one query.
users, err := db.Users.OrderBy(&Users.Name).All(ctx)
err = db.Users.Load(ctx, &Users.Posts, users...)
err = db.Posts.LoadOne(ctx, &Posts.User, post)
// SELECT ... FROM "posts" WHERE "posts"."user_id" IN ($1, $2)
// SELECT ... FROM "users" WHERE "users"."id" IN ($1)
Loading again replaces the rows already there. Passing the same entity twice loads it once. LoadMissing skips entities whose relation is already loaded. ant.Pointers adapts a []T, as from ant.Raw.
rows, err := ant.Raw[User](db, `SELECT * FROM users`).All(ctx)
err = db.Users.LoadMissing(ctx, &Users.Posts, ant.Pointers(rows)...)
Query one entity's related rows
ant.Related starts a query from one entity's relation, which you can refine, count, or delete. ant.RelatedOne does the same for a *T relation. Neither fills the entity's field.
drafts, err := ant.Related(db, alice, &Users.Posts).
Where(ant.Eq(&Posts.Published, false)).
OrderBy(&Posts.Title).
All(ctx)
author, err := ant.RelatedOne(db, post, &Posts.User).Single(ctx)
// SELECT ... FROM "posts" WHERE "posts"."user_id" = $1 AND "posts"."published" = $2 ORDER BY "posts"."title"
// SELECT ... FROM "users" WHERE "users"."id" = $1 LIMIT $2
Counts and sums
Fill a computed field with an aggregate of a relation. The aggregate is a subquery in the same statement.
type Writer struct {
ID int64
Articles []Article
ArticleCount int64 `ant:"computed"`
TotalViews int `ant:"computed"`
AverageViews sql.Null[float64] `ant:"computed"`
}
type Article struct {
ID int64
WriterID int64
Views int
Live bool
}
var (
Writers = ant.Fields[Writer]()
Articles = ant.Fields[Article]()
)
writers, err := db.Writers.
With(&Writers.ArticleCount, ant.CountRelated(&Writers.Articles, ant.Eq(&Articles.Live, true))).
With(&Writers.TotalViews, ant.SumRelated(&Writers.Articles, &Articles.Views)).
With(&Writers.AverageViews, ant.AvgRelated(&Writers.Articles, &Articles.Views)).
All(ctx)
// SELECT "writers"."id",
// (SELECT COUNT(*) FROM "articles" AS "ant_related"
// WHERE "ant_related"."writer_id" = "writers"."id" AND ("ant_related"."live" = $1)) AS "article_count",
// (SELECT COALESCE(SUM("ant_related"."views"), 0) FROM "articles" AS "ant_related"
// WHERE "ant_related"."writer_id" = "writers"."id") AS "total_views",
// (SELECT AVG("ant_related"."views") FROM "articles" AS "ant_related"
// WHERE "ant_related"."writer_id" = "writers"."id") AS "average_views"
// FROM "writers"
CountRelated and SumRelated give zero when there are no rows. AvgRelated, MinRelated, and MaxRelated give NULL, so they need a nullable field.
See it tested: tests/features/loading