1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Gormのhas manyなテーブルのAutoMigrate()でneed to define a foreign keyと怒られる

Last updated at Posted at 2020-11-16

#ドキュメントのhas manyを見る
https://gorm.io/docs/has_many.html
##追記
根本的に間違っていました。
同じような間違いをしている誰かの参考になればと思います。

#エラー内容

// 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のWorksheetsには特に外部キーの指定等をしていません
すると・・・

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

外部キーを定義しなさいと怒られます。
#改善コード

// Vote model
type Vote struct {
	gorm.Model
	ID          uint
	Title       string
	Description string
    //外部キーの定義を追加
	WorkSheets  []Worksheet `gorm:"foreignKey:ID"`
}

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

WorksheetのIDを外部キーにしています

#本当の解決

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

// Worksheet model
type Worksheet struct {
	gorm.Model
	Text       string
  //追加
	VoteID     int
	VoteNumber int
}

has manyのmany側に、主キー用のフィールドを追加しておく必要があったようです。
完全に勘違いしていました。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?