0

I'm working on a Gin app using Gorm ORM (I'm new to both of them). I've got the following model:

type Record struct {
    Barcode             string `json:"barcode" gorm:"size:48;unique;not null" sql:"index"`
    Name                string `json:"name" gorm:"size:160;unique;not null"`
    Artist              Artist `gorm:"foreignKey:ArtistID""`
    ArtistId            uint
    Category            Category `gorm:"foreignKey:CategoryID"`
    CategoryId          uint
    NumOfRecords        int       `json:"num_of_records" gorm:"not null"`
    OriginalReleaseDate time.Time `json:"original_release_date" gorm:"default:null"`
    ReissueReleaseDate  time.Time `json:"reissue_release_date" gorm:"default:null"`
    SideColor           string    `json:"side_color" gorm:"default:null"`
    BarcodeInRecord     bool      `json:"barcode_in_record" gorm:"default=true"`
    gorm.Model
}

As you can see there are two fields with two foreign keys: Artist and Category. Here's those models:

type Category struct {
    Name        string `json:"name" gorm:"size:60;unique;not null"`
    Description string `json:"description" gorm:"size:120"`
    Parent      uint   `json:"parent" gorm:"default:null"`
    Active      bool   `json:"active" gorm:"default:true"`
    gorm.Model
}
type Artist struct {
    Name            string `json:"name" gorm:"size:120;unique;not null"`
    Type            string `json:"type" gorm:"default:null"`
    CountryOfOrigin string `json:"countryOfOrigin" gorm:"default:null"`
    gorm.Model
}

category_id and artist_id columns are being created but they are not referencing the other tables two tables:

enter image description here

I've tried to define those fields using AssociationForeignKey:Refer. I also tried to change the foreign key name to simply ID since that's the name that GORM assigns to primary keys but none of those thinks have worked.

What am I missing?

MrCujo
  • 1,218
  • 3
  • 31
  • 56
  • When you say "not referencing the other two tables", what do you mean? The `Category` and `Artist` fields of the `Record` struct are not being loaded? If this is the case, could you show the code where you are trying to load data for the `Record` model? – Emin Laletovic Apr 23 '22 at 08:06
  • As you can see in the picture, the foreign_key column in the table description should show the pk in Categories and Artists tables respectively, but they are empty – MrCujo Apr 23 '22 at 13:27

1 Answers1

0

IMO Gorm docs are pretty lousy. From another SO question (Gorm Golang orm associations) it is said that:

it doesn't (create FKs when migrations run). If you want Foreign Key in DB, you need explicitly write something like db.Model(&Place{}).AddForeignKey("town_id", "towns(id)", "RESTRICT", "RESTRICT") during your migrations.

MrCujo
  • 1,218
  • 3
  • 31
  • 56