Many-to-many
A many-to-many relation goes through a join table. Declare it on either side or both; migrations create the table once.
Declare a many-to-many relation
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]()
Courses = ant.Fields[Course]()
)
The join table's columns default to student_id and course_id here.
Name the join columns
PivotColumns names them. A self-referencing relation needs it, because both columns would otherwise get the same name.
type Person struct {
ID int64
Friends []Person
}
func (Person) Configure(b *ant.ModelBuilder[Person]) {
b.ManyToMany(&Persons.Friends).Through("friendships").PivotColumns("person_id", "friend_id")
}
var Persons = ant.Fields[Person]()
Read through the join table
Include, Has, JoinMany, and CountRelated all go through the join table. Include reads the join table, then the targets: one query more than a one-to-many Include.
students, err := db.Students.Include(&Students.Courses).All(ctx)
// SELECT "students"."id", "students"."name" FROM "students"
// SELECT "student_id", "course_id" FROM "enrollments" WHERE "student_id" IN ($1)
// SELECT "courses"."id", "courses"."title" FROM "courses" WHERE "courses"."id" IN ($1)
artists, err := db.Students.Where(ant.Has(&Students.Courses, ant.Eq(&Courses.Title, "Art"))).All(ctx)
// SELECT ... FROM "students" WHERE EXISTS (
// SELECT 1 FROM "courses" AS "ant_related"
// JOIN "enrollments" AS "ant_related_pivot" ON "ant_related_pivot"."course_id" = "ant_related"."id"
// WHERE "ant_related_pivot"."student_id" = "students"."id" AND ("ant_related"."title" = $1))
Change the links
These functions change the join table only, never the rows on either side. Both entities must already have their keys.
err := ant.Link(ctx, db, ann, &Students.Courses, math, art) // add
// INSERT INTO "enrollments" ("student_id", "course_id") VALUES ($1, $2), ($3, $4) ON CONFLICT DO NOTHING
err = ant.Unlink(ctx, db, ann, &Students.Courses, art) // remove
// DELETE FROM "enrollments" WHERE "student_id" = $1 AND "course_id" IN ($2)
err = ant.SyncLinks(ctx, db, ann, &Students.Courses, art, music) // make the list exact
// DELETE FROM "enrollments" WHERE "student_id" = $1 AND NOT ("course_id" IN ($2, $3))
// INSERT INTO "enrollments" ("student_id", "course_id") VALUES ($1, $2), ($3, $4) ON CONFLICT DO NOTHING
err = ant.Toggle(ctx, db, ann, &Students.Courses, math) // flip each one
// DELETE FROM "enrollments" WHERE "student_id" = $1 AND "course_id" IN ($2) RETURNING "course_id"
// INSERT INTO "enrollments" ("student_id", "course_id") VALUES ($1, $2) ON CONFLICT DO NOTHING
Repeating a Link is harmless, because the insert ignores existing links. SyncLinks leaves the table matching the list you pass. Toggle removes the links that exist and adds the ones that don't.
Change the links through a tracked slice
Edit a loaded relation like any slice and SaveChanges updates the links. A new target is inserted and linked. Removing one removes the link, never the course.
session := ant.Session(db)
student, err := session.Students.Include(&Students.Courses).Find(ctx, id)
student.Courses = student.Courses[1:]
student.Courses = append(student.Courses, Course{Title: "Drama"})
err = session.SaveChanges(ctx)
Setting an element to another course unlinks the old one and links the new one. Loading the relation again before saving discards pending changes to the slice: save first.
A new owner inserted with existing targets links them in the same call. On a session, it is tracked as if loaded with them:
session := ant.Session(db)
cal := &Student{Name: "Cal", Courses: []Course{*math}}
err := session.Students.Insert(ctx, cal)
// INSERT INTO "students" ("name") VALUES ($1) RETURNING "id"
// INSERT INTO "enrollments" ("student_id", "course_id") VALUES ($1, $2) ON CONFLICT DO NOTHING
Keep data on the join table
When the join table holds data of its own, like a grade or a date, make it a model with two has-many relations. It gets queries, timestamps, and hooks like any other model. ant has no separate pivot API.
type Enrollment struct {
ant.Base
StudentID int64
CourseID int64
Grade *string
}
See it tested: tests/features/relations/many_to_many_test.go