gorm icon indicating copy to clipboard operation
gorm copied to clipboard

How to create foreign key for embedded hasmany relation during migration?

Open StephanoGeorge opened this issue 2 years ago • 0 comments

Your Question

How to create foreign key for embedded hasmany relation during migration? For example:

type VirtualMachine struct {
	gorm.Model
	AccountID uint
	Account   Account
}

type Disk struct {
	gorm.Model
	AccountID uint
	Account   Account
}

type Database struct {
	gorm.Model
	AccountID uint
	Account   Account
}

type Domain struct {
	gorm.Model
	AccountID uint
	Account   Account
}

type Resources struct {
	VirtualMachines []*VirtualMachine
	Disks           []*Disk
	Databases       []*Database
	Domains         []*Domain
}

type Account struct {
	gorm.Model
	Name string
	Resources
}

func main() {
	db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{})
	check(err)
	err = db.AutoMigrate(&Account{}, &VirtualMachine{}, &Disk{}, &Database{}, &Domain{})
	check(err)
}

func check(err error) {
	if err != nil {
		panic(err)
	}
}

GORM will not create foreign keys virtual_machine.account_id -> account.id and so on. This is caused by: https://github.com/go-gorm/gorm/blob/9d82aa56734999bb28e0c4d60fba69ae7cde66d5/schema/relationship.go#L95-L96. So, if I move fields in Resources to Account, GORM will create foreign keys, but can I keep Resources struct independent?

The document you expected this should be explained

Expected answer

The solution that I can keep Resources struct independent, and GORM also creates foreign keys.

StephanoGeorge avatar Oct 27 '22 07:10 StephanoGeorge