Changing relations
Load a relation with Include, change the slice or pointer, and call SaveChanges. ant compares each relation with the rows it held at load, by key, so append, slices.Delete and reordering are safe.
Add a child
An appended element is inserted. Its new key and its foreign key are copied back into the element.
session := ant.Session(db)
alice, err := session.Users.Include(&Users.Posts).Find(ctx, id)
alice.Posts = append(alice.Posts, Post{Title: "New"})
err = session.SaveChanges(ctx)
// INSERT INTO "posts" ("created_at", "updated_at", "user_id", "title", "published")
// VALUES ($1, $2, $3, $4, $5) RETURNING "id"
A relation set on a new entity works the same. Insert writes the children and tracks the entity as if loaded with them, so removing one later deletes it and an unrelated edit doesn't rewrite the children or a join table:
dave := &User{Name: "Dave", Email: "dave@example.com", Posts: []Post{{Title: "A"}, {Title: "B"}}}
err := session.Users.Insert(ctx, dave)
// INSERT INTO "users" (...) VALUES (...) RETURNING "id"
// INSERT INTO "posts" (...) VALUES (...), (...) RETURNING "id"
dave.Posts = dave.Posts[:1]
err = session.SaveChanges(ctx)
// DELETE FROM "posts" WHERE "posts"."id" = $1
InsertOnly ignores relations, so it records none.
Edit a child
alice.Posts[0].Title = "Edited"
err := session.SaveChanges(ctx)
// UPDATE "posts" SET "title" = $1, "updated_at" = $2 WHERE "posts"."id" = $3
Remove a child
Removal depends on the foreign key. Post.UserID is required, so a removed post is deleted.
alice.Posts = slices.Delete(alice.Posts, 0, 1) // deletes that post
alice.Posts = alice.Posts[:1] // deletes the rest but one
alice.Posts = nil // deletes them all
err := session.SaveChanges(ctx)
// DELETE FROM "posts" WHERE "posts"."id" = $1
A nullable foreign key is unlinked instead: the child stays, with no parent. Nullable means its zero value is written as NULL: a pointer, or a type such as sql.Null[T]. A uuid.UUID key is not, so a removed child with one is deleted rather than given the zero UUID, and so is one whose column is configured NotNull.
type Member struct {
ant.Base
Name string
TeamID *int64 // nullable, so removal clears it
Team *Team
}
type Team struct {
ant.Base
Name string
Members []Member
}
An unloaded relation is nil and removes nothing.
user, err := session.Users.Find(ctx, id)
user.Age = 31
err = session.SaveChanges(ctx) // user.Posts is nil, and the posts are safe
Move a child to another parent
Move the child between slices. ant updates its foreign key instead of deleting it.
post := alice.Posts[0]
bob.Posts = append(bob.Posts, post)
alice.Posts = alice.Posts[1:]
err := session.SaveChanges(ctx)
// UPDATE "posts" SET "user_id" = $1, "updated_at" = $2 WHERE "posts"."id" = $3
The new parent can be a new entity saved in the same call, or a loaded one whose relation wasn't loaded. Either way the child is moved:
team, err := session.Teams.Include(&Teams.Members).Find(ctx, id)
member := team.Members[0]
team.Members = team.Members[1:]
other := &Team{Name: "Platform", Members: []Member{member}}
err = ant.Add(ctx, session, other)
err = session.SaveChanges(ctx)
// INSERT INTO "teams" ("created_at", "updated_at", "name") VALUES ($1, $2, $3) RETURNING "id"
// UPDATE "members" SET "team_id" = $1, "updated_at" = $2 WHERE "members"."id" = $3
Setting post.UserID also works, even with post.User loaded: a relation that still holds what was loaded leaves the foreign key alone.
Change a parent
Set the pointer or the foreign key. A new parent is inserted and linked, and nil clears a nullable key. If both change, the foreign key wins.
member, err := session.Members.IncludeOne(&Members.Team).Find(ctx, id)
member.Team = &Team{Name: "New team"}
err = session.SaveChanges(ctx)
// INSERT INTO "teams" ("created_at", "updated_at", "name") VALUES ($1, $2, $3) RETURNING "id"
// UPDATE "members" SET "team_id" = $1, "updated_at" = $2 WHERE "members"."id" = $3
A pointer is remembered once a save has written it, so setting it and clearing it across two saves unlinks the row:
member, err := session.Members.IncludeOne(&Members.Team).Find(ctx, id)
member.Team = &Team{Name: "New team"}
err = session.SaveChanges(ctx)
member.Team = nil
err = session.SaveChanges(ctx)
// UPDATE "members" SET "team_id" = $1, "updated_at" = $2 WHERE "members"."id" = $3 -- $1 = NULL
A pointer that was empty when loaded and is still empty leaves the foreign key to you.
Change a many-to-many link
Appending to a many-to-many slice links, removing unlinks, and the target rows stay.
type Student struct {
ID int64
Name string
Courses []Course
}
func (Student) Configure(b *ant.ModelBuilder[Student]) {
b.ManyToMany(&Students.Courses).Through("enrollments")
}
type Course struct {
ID int64
Title string
}
var Students = ant.Fields[Student]()
Overwriting an element unlinks the old course and links the new one.
ann, err := session.Students.Include(&Students.Courses).Find(ctx, id)
ann.Courses[0] = *rust
err = session.SaveChanges(ctx)
// DELETE FROM "enrollments" WHERE "student_id" = $1 AND "course_id" IN ($2)
// INSERT INTO "enrollments" ("student_id", "course_id") VALUES ($1, $2) ON CONFLICT DO NOTHING
See many-to-many for the declaration.
Nested includes
Relations loaded below a slice element are tracked on it too. In a category tree loaded two levels deep, removing a grandchild from a child's slice unlinks it and appending one inserts it.
type Category struct {
ID int64
ParentID *int64
Name string
Parent *Category
Children []Category
}
var Categories = ant.Fields[Category]()
root, err := session.Categories.
Include(&Categories.Children, func(q *ant.Query[Category]) *ant.Query[Category] {
return q.Include(&Categories.Children)
}).
Find(ctx, id)
child := &root.Children[0]
child.Children = append(child.Children[:1], Category{Name: "New"}) // drops the second, adds one
err = session.SaveChanges(ctx)
// UPDATE "categories" SET "parent_id" = $1 WHERE "categories"."id" = $2 -- $1 = NULL
// INSERT INTO "categories" ("parent_id", "name") VALUES ($1, $2) RETURNING "id"
Remove an unsaved entity
ant.Remove on an entity that was added and never saved cancels its insert, so nothing is written.
post := &Post{UserID: alice.ID, Title: "Draft"}
err := ant.Add(ctx, session, post)
err = ant.Remove(ctx, session, post)
has, err := session.HasChanges(ctx)
// has is false
See the changes before saving
HasChanges plans the real save, so it sees a child added to, removed from or moved between loaded relations, as well as edited fields.
alice.Posts = append(alice.Posts, Post{Title: "C"})
has, err := session.HasChanges(ctx)
// has is true, and nothing was written
A later Include reads again
Include on a tracked parent reads its relation afresh, as Load does, and replaces unsaved changes to that relation. Call SaveChanges first to keep them.
See it tested: tests/features/change_tracking/relations_test.go