Skip to main content

Advanced relations

Reach across a table in the middle​

HasManyThrough reaches across a table in the middle: a country's articles, by way of its members. HasOneThrough does the same for one row. They load like any other relation but are never written, because those rows belong to the models in the middle.

type Country struct {
ID int64
Name string
Articles []Article
Top *Article
}

func (Country) Configure(b *ant.ModelBuilder[Country]) {
b.HasManyThrough(&Countries.Articles, &Members.CountryID, &Articles.MemberID)
b.HasOneThrough(&Countries.Top, &Members.CountryID, &Articles.MemberID)
}

type Member struct {
ID int64
CountryID int64
}

type Article struct {
ID int64
MemberID int64
Title string
}

var (
Countries = ant.Fields[Country]()
Members = ant.Fields[Member]()
Articles = ant.Fields[Article]()
)

countries, err := db.Countries.Include(&Countries.Articles).All(ctx)
// SELECT ... FROM "countries"
// SELECT "country_id", "id" FROM "members" WHERE "country_id" IN ($1)
// SELECT ... FROM "articles" WHERE "articles"."member_id" IN ($1)

Has and counts work through the middle table as well:

withArticles, err := db.Countries.Where(ant.Has(&Countries.Articles)).All(ctx)
// SELECT ... FROM "countries" WHERE EXISTS (
// SELECT 1 FROM "articles" AS "ant_related"
// JOIN "members" AS "ant_related_pivot" ON "ant_related_pivot"."id" = "ant_related"."member_id"
// WHERE "ant_related_pivot"."country_id" = "countries"."id")

Share a table between several owners​

A polymorphic relation uses one foreign key for several tables, plus a second column saying which table, as for comments that can belong to an essay or a video. Essay 1 and Video 1 can share a key and each sees only its own comments. Saving through the relation sets the type column.

type Comment struct {
ID int64
OwnerID int64
OwnerType string
Text string
Essay *Essay
Video *Video
}

func (Comment) Configure(b *ant.ModelBuilder[Comment]) {
b.BelongsTo(&Comments.Essay).ForeignKey(&Comments.OwnerID).Morph(&Comments.OwnerType, "essay")
b.BelongsTo(&Comments.Video).ForeignKey(&Comments.OwnerID).Morph(&Comments.OwnerType, "video")
}

type Essay struct {
ID int64
Comments []Comment
}

func (Essay) Configure(b *ant.ModelBuilder[Essay]) {
b.HasMany(&Essays.Comments).ForeignKey(&Comments.OwnerID).Morph(&Comments.OwnerType, "essay")
}

type Video struct {
ID int64
Comments []Comment
}

func (Video) Configure(b *ant.ModelBuilder[Video]) {
b.HasMany(&Videos.Comments).ForeignKey(&Comments.OwnerID).Morph(&Comments.OwnerType, "video")
}

var (
Comments = ant.Fields[Comment]()
Essays = ant.Fields[Essay]()
Videos = ant.Fields[Video]()
)

Both sides of each relation need the same .Morph, or the relation is read with the wrong type.

essays, err := db.Essays.Include(&Essays.Comments).All(ctx)
// SELECT ... FROM "essays"
// SELECT ... FROM "comments" WHERE "comments"."owner_type" = $1 AND "comments"."owner_id" IN ($2)
// $1 = 'essay'

The stored value is the one you give .Morph, so renaming a Go type doesn't change data. Migrations write no foreign key here, because one column can't point at several tables.

Scoped relations and latest of many​

A relation can carry a condition or pick one row per parent. Live is a "published novels" relation. Newest is the single most recent novel.

type Novelist struct {
ID int64
Novels []Novel
Live []Novel
Newest *Novel
}

func (Novelist) Configure(b *ant.ModelBuilder[Novelist]) {
b.HasMany(&Novelists.Live).ForeignKey(&Novels.NovelistID).Where(ant.Eq(&Novels.Published, true))
b.HasOne(&Novelists.Newest).ForeignKey(&Novels.NovelistID).Latest(&Novels.Year)
}

type Novel struct {
ID int64
NovelistID int64
Year int
Published bool
Novelist *Novelist
}

var (
Novelists = ant.Fields[Novelist]()
Novels = ant.Fields[Novel]()
)
novelists, err := db.Novelists.Include(&Novelists.Live).IncludeOne(&Novelists.Newest).All(ctx)
// SELECT ... FROM "novelists"
// SELECT ... FROM "novels" WHERE "novels"."published" = $1 AND "novels"."novelist_id" IN ($2)
// SELECT * FROM (
// SELECT ..., ROW_NUMBER() OVER (PARTITION BY "novels"."novelist_id" ORDER BY "novels"."year" DESC) AS "ant_row"
// FROM "novels" WHERE "novels"."novelist_id" IN ($1)
// ) AS "ant_partition" WHERE "ant_partition"."ant_row" > $2 AND "ant_partition"."ant_row" <= $3

Counts, Has and joins follow the scope. .Oldest is the opposite of .Latest. For a one-off filter that isn't part of the model, use a shaped Include instead.

Fill the way back​

Inverse points each child at its parent, with no query.

func (Novelist) Configure(b *ant.ModelBuilder[Novelist]) {
b.HasMany(&Novelists.Novels).ForeignKey(&Novels.NovelistID).Inverse(&Novels.Novelist)
}

After Include(&Novelists.Novels), novels[0].Novelist is the same instance as its parent.

Touching the parent​

Touch moves a parent's UpdatedAt when a child is written.

type Answer struct {
ID int64
DiscussionID int64
Discussion *Discussion
}

func (Answer) Configure(b *ant.ModelBuilder[Answer]) {
b.BelongsTo(&Answers.Discussion).Touch()
}

type Discussion struct {
ID int64
UpdatedAt time.Time
}

var Answers = ant.Fields[Answer]()

Saving an answer then also runs:

// UPDATE "discussions" SET "updated_at" = $1 WHERE "discussions"."id" = $2