简体   繁体   中英

Go Gorm: Foreign key not present in table creation

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:

在此处输入图像描述

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM