Search code examples
gogo-gormgo-gin

GO - Gin/Gorm/Postgresql - Create a foreignKey with "has one" association


I've read the documentation (https://gorm.io/docs/has_one.html) and tested as suggested but I can't create the association. My tables look like this (the names are in Italian)

models/tables.go

type TeatroY struct {
    gorm.Model
    Nome  string
    Posti int
}

type SpettacoloXY struct {
    gorm.Model
    Nome   string
    Teatro TeatroY `gorm:"foreignKey:id"`
}

and in the main I use the classic automigrate

initializers.DB.AutoMigrate(&models.TeatroY{}, &models.SpettacoloXY{})

The error I get is as follows

"2023/04/02 16:12:24 E:/Work/Mota/cdbp4/server.go:13 ERROR: relation "spettacolo_xies" does not exist (SQLSTATE 42P01) [33.459ms] [rows:0] ALTER TABLE "teatro_ies" ADD CONSTRAINT "fk_spettacolo_xies_teatro" FOREIGN KEY ("id") REFERENCES "spettacolo_xies"("id")"

After create a "TeatroY", when I create a "SpettacoloXY" the "Teatro" field must be associated with one and only one "TeatroY"

Thanks in advance for the help


Solution

  • Changing the model migration code to this:

    initializers.DB.AutoMigrate(&models.SpettacoloXY{}, &models.TeatroY{})
    

    will get rid of the error and will create both tables in the database.