go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
36.91k stars 3.93k forks source link

Custom Polymorphic Fields #5764

Open hendraptaksu opened 2 years ago

hendraptaksu commented 2 years ago

Your Question

Is there a way to change the polymorphic fields type and id naming convetion? Currently in the docs the only way to use polymorphic feature is to follow polymorphic+"ID", polymorphic+"Type" naming convetion. I wanted to use polymorphic+"Id" instead of polymorphic+"ID". Is this thing possible to achieve? Thank You in advance.

The document you expected this should be explained

Expected answer

revenkroz commented 1 year ago

I had the same question. Ended this way:


type Project struct {
    Name      string `json:"name"`
    OwnerID   int    `gorm:"column:id" json:"id"`
    OwnerType string `gorm:"column:type" json:"type"`
}

type Movie struct {
    Project Project `gorm:"polymorphic:Owner;" json:"-"`
    Id      int     `json:"id"`
    Status  string  `json:"status"`
}

So I just renamed columns for fields OwnerID and OwnerType.