简体   繁体   English

Go Gorm:表创建中不存在外键

[英]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).我正在使用 Gorm ORM 开发一个 Gin 应用程序(我对他们两个都是新手)。 I've got the following model:我有以下 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:正在创建category_idartist_id列,但它们没有引用其他表两个表:

在此处输入图像描述

I've tried to define those fields using AssociationForeignKey:Refer .我尝试使用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.我还尝试将外键名称更改为简单的ID ,因为这是 GORM 分配给主键的名称,但这些都没有奏效。

What am I missing?我错过了什么?

IMO Gorm docs are pretty lousy. IMO Gorm 文档非常糟糕。 From another SO question ( Gorm Golang orm associations ) it is said that:从另一个 SO 问题( Gorm Golang orm associations )中可以看出:

it doesn't (create FKs when migrations run).它不会(在迁移运行时创建 FK)。 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.如果你想在数据库中使用外键,你需要在迁移过程中明确地写一些像 db.Model(&Place{}).AddForeignKey("town_id", "towns(id)", "RESTRICT", "RESTRICT") 这样的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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