GORM Playground Link

https://go.dev/play/p/H0kaUoRuJeh

Description

Has-many relationships appear to require explicit definition of a foreign key when embedding gorm.Model. Per the link in the playground:

type Poll struct {
    gorm.Model
    Name     string
    Question string
    Choices  []Choice // `gorm:"foreignKey:ID"`
    Expires  time.Time
}

type Choice struct {
    gorm.Model
    Text  string
    Votes int
}
...
    if err := db.AutoMigrate(&model.Poll{}, &model.Choice{}); err != nil {
        panic(err)
    }

The code above fails to auto migrate with the following error:

[error] invalid field found for struct github.com/brakthehack/poll/app/model.Poll's field Choices: define a valid foreign key for relations or implement the Valuer/Scanner interface

The auto migration script should be able to guess that the FK for Poll.Choices should be the ID field of the Choice model. When the FK is explicitly added by removing the comments before the gorm tag, the code works successfully. The documentation also seems to suggest this should work in the first example by emitting the explicit foreignKey tag.

go version go1.19 linux/amd64

gorm.io/driver/postgres v1.3.8 // indirect
gorm.io/gorm v1.23.8 // indirect

Comment From: a631807682

https://gorm.io/docs/has_many.html#Declare

// User has many CreditCards, UserID is the foreign key

type Choice struct {
    gorm.Model
    Text  string
    Votes int
+   PollId uint
}