Polymorphic relations
One notes table pointing back at many owner types via polymorphic:owner — OwnerID/OwnerType columns, preloading, and writes.
The tag
Adding polymorphic:<name> to a has-one or has-many tag turns the relation
into a polymorphic one. Instead of a dedicated foreign-key column, the
target table stores two columns derived from <name>:
<name>_id— the owner's primary key,<name>_type— a string discriminator naming the owner type.
type polyOwner struct {
ID int64 `fusion:"pk,autoincrement"`
Name string
Notes []polyNote `fusion:"rel:has-many,polymorphic:owner"`
}
type polyNote struct {
ID int64 `fusion:"pk,autoincrement"`
OwnerID int64
OwnerType string
Body string
}The discriminator value is the polymorphic: tag value itself — here
"owner". If you omit the value, it defaults to the snake-cased owner model
name (schema/relation.go:77):
if value, ok := tag.Lookup("polymorphic"); ok {
rel.Polymorphic = true
rel.PolymorphicValue = value
if rel.PolymorphicValue == "" {
rel.PolymorphicValue = snakeModel(table.Type.Name())
}
rel.PolymorphicField = lookupField(join, rel.PolymorphicValue+"_type")
}Because the default is the owner model's name, two different owners can
share one notes table without colliding: each writes a distinct
<name>_type string.
The type filter is always applied
For a polymorphic relation, the _type filter is added to every preload
query — it is not optional. The <name>_type column is located by DB column
name or Go field name; if neither matches, the child query references a
column that does not exist and fails. Name the field to match, or alias it
with fusion:"column:...".
Preloading
Preload works for polymorphic relations like any has-many. The child query
filters both columns (preload.go:199):
SELECT * FROM "poly_notes" WHERE "owner_id" IN (?) AND "owner_type" = ?The bound type value is the relation's discriminator, "owner".
The type filter is what keeps unrelated rows out. With this seed data:
db.Create(&[]polyNote{
{ID: 1, OwnerID: 1, OwnerType: "owner", Body: "go note"},
{ID: 2, OwnerID: 1, OwnerType: "owner", Body: "sql note"},
{ID: 3, OwnerID: 1, OwnerType: "other", Body: "foreign note"},
})the preload loads exactly two notes for owner 1 — note 3 has the right
owner_id but the wrong type (relation_test.go:419):
var owner polyOwner
if err := db.Model(&polyOwner{}).Preload("Notes").First(&owner, 1).Error; err != nil {
t.Fatal(err)
}
// len(owner.Notes) == 2 — the "other"-type note is excludedFilter args and apply functions compose as usual:
Preload("Notes", "body = ?", "sql note") narrows to one note
(relation_test.go:434).
Writing polymorphic rows
Append on a polymorphic association sets both columns before saving the
child (association.go:156):
if a.rel.Polymorphic {
field = childTable.Column(a.db.NamingStrategy.ColumnName("", a.rel.PolymorphicValue+"_id"))
if field == nil {
return fmt.Errorf("%w: %s has no polymorphic id column", ErrInvalidRelation, childTable.Name)
}
typeField := childTable.Column(a.db.NamingStrategy.ColumnName("", a.rel.PolymorphicValue+"_type"))
if typeField != nil {
if err := setFieldValue(item, typeField, a.rel.PolymorphicValue); err != nil {
return err
}
}
}The same happens during Create — saving a polyOwner with populated
Notes writes each note's owner_id and owner_type through the
association callbacks. Association.Clear respects the type too: it nulls
only rows where owner_type matches the relation's discriminator
(association.go:404).
Schema requirements
The target table needs the two generated column names. With the default
NamingStrategy and polymorphic:owner:
CREATE TABLE "poly_notes" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"owner_id" INTEGER,
"owner_type" TEXT,
"body" TEXT
)AutoMigrate creates these columns from the polyNote struct — the
OwnerID/OwnerType field names map to owner_id/owner_type, matching
what the relation machinery expects. If your struct names differ from the
<name>_id/<name>_type convention, alias them with fusion:"column:...".