0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Goでマイグレーションしようした時の構造体のタイポによるエラー

Posted at

構造体の定義

type Shop struct {
	ID        uint      `json:"id" gorm:"primaryKey"`
	ShopName  string    `json:"shopname" gorm:"not null"`
	Place     string    `json:"place"`
	Location  float64   `json:"location"`
	Price     uint      `json:"price"`
	Tag       string    `json:"tag"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	User      User      `json:"user" gorm:"foreignKey:UserID; constraint:OnDelete:CASCADE"`
	UserId    uint      `json:"userid"`
}

上記のコードのままmigrationを実行しようとしたら、エラーが出てDBと接続できませんでした。

原因はUserのフィールドで外部キーの記述の部分でタイポでした。。。情けない。。正しくは下記のように定義します。

正しい構造体の定義

type Shop struct {
	ID        uint      `json:"id" gorm:"primaryKey"`
	ShopName  string    `json:"shopname" gorm:"not null"`
	Place     string    `json:"place"`
	Location  float64   `json:"location"`
	Price     uint      `json:"price"`
	Tag       string    `json:"tag"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
	User      User      `json:"user" gorm:"foreignKey:UserID; constraint:OnDelete:CASCADE"`
	UserID    uint      `json:"userid"`
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?