Gorm has many tables AutoMigrate () gets angry with need to define a foreign key

See has many in the docs

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

Postscript

It was fundamentally wrong. I hope it helps someone who makes similar mistakes.

error contents

// Vote model
type Vote struct {
	gorm.Model
	ID          uint
	Title       string
	Description string
	WorkSheets  []Worksheet
}

// Worksheet model
type Worksheet struct {
	gorm.Model
	ID         uint
	Text       string
	VoteNumber uint
}

~~ Vote's Worksheets do not have any foreign keys specified Then ... ~~

invalid field found for struct main.Vote's field WorkSheets,
need to define a foreign key for relations or it need to implement the Valuer/Scanner interface

~~ I get angry when I define a foreign key. ~~

Improvement code

// Vote model
type Vote struct {
	gorm.Model
	ID          uint
	Title       string
	Description string
    //Added foreign key definition
	WorkSheets  []Worksheet `gorm:"foreignKey:ID"`
}

// Worksheet model
type Worksheet struct {
	gorm.Model
	ID         uint
	Text       string
	VoteNumber uint
}

~~ Worksheet ID is used as a foreign key ~~

Real solution

// Vote model
type Vote struct {
	gorm.Model
	Title       string
	Description string
	WorkSheets  []Worksheet
}

// Worksheet model
type Worksheet struct {
	gorm.Model
	Text       string
  //add to
	VoteID     int
	VoteNumber int
}

It seems that it was necessary to add a field for the primary key on the many side of has many. I was completely misunderstood.

Recommended Posts

Gorm has many tables AutoMigrate () gets angry with need to define a foreign key
If you specify a foreign key in Django's model change, you need to specify on_delete.