Filtering by relations
ant.Has and its relatives filter rows by their related rows. Each becomes an EXISTS in the same query and loads nothing. To load the related rows too, use Include.
Rows that have a related row
writers, err := db.Users.Where(ant.Has(&Users.Posts)).All(ctx)
// SELECT ... FROM "users" WHERE EXISTS (
// SELECT 1 FROM "posts" AS "ant_related" WHERE "ant_related"."user_id" = "users"."id")
Conditions on the related row narrow the match. This finds users with an unpublished post:
drafting, err := db.Users.Where(ant.Has(&Users.Posts, ant.Eq(&Posts.Published, false))).All(ctx)
// SELECT ... FROM "users" WHERE EXISTS (
// SELECT 1 FROM "posts" AS "ant_related"
// WHERE "ant_related"."user_id" = "users"."id" AND ("ant_related"."published" = $1))
Rows with no related row
silent, err := db.Users.Where(ant.HasNone(&Users.Posts)).All(ctx)
// SELECT ... FROM "users" WHERE NOT EXISTS (
// SELECT 1 FROM "posts" AS "ant_related" WHERE "ant_related"."user_id" = "users"."id")
With conditions, HasNone matches rows with no related row meeting them, so these users may still have drafts:
unpublished, err := db.Users.Where(ant.HasNone(&Users.Posts, ant.Eq(&Posts.Published, true))).All(ctx)
This is also how to delete with a join.
Follow a relation to its owner
ant.HasOne follows a many-to-one or one-to-one relation, so a child can be filtered by its parent.
byAdults, err := db.Posts.Where(ant.HasOne(&Posts.User, ant.Gt(&Users.Age, 18))).All(ctx)
// SELECT ... FROM "posts" WHERE EXISTS (
// SELECT 1 FROM "users" AS "ant_related"
// WHERE "ant_related"."id" = "posts"."user_id" AND ("ant_related"."age" > $1))
Combine with other conditions
They go in Where beside other conditions and inside And, Or, and Not.
young, err := db.Users.Where(ant.Has(&Users.Posts), ant.Lt(&Users.Age, 18)).All(ctx)
// SELECT ... FROM "users" WHERE EXISTS (...) AND "users"."age" < $1
same, err := db.Users.Where(ant.Not(ant.Has(&Users.Posts))).Count(ctx)
// SELECT COUNT(*) FROM "users" WHERE NOT (EXISTS (...))
They work on many-to-many and through relations too.
A global filter on the related model still applies, and so does a scope on the relation.
ant.Has needs the related model's configuration, which exists once a context has opened. Call it where the query is built, not in a package variable.
See it tested: tests/features/relations/has_test.go