I'm trying to setup relation between two models on PostgreSQL database using Go and gorm.
Here is my code, first model:
package model
import "github.com/jinzhu/gorm"
// Trip models
type Trip struct {
gorm.Model
TripName string
TripDescription string
}
Second model:
package model
import "github.com/jinzhu/gorm"
// TripKeyPoint models
type TripKeyPoint struct {
gorm.Model
KPName string
KPDescription string
TripID Trip
}
Part of code from a file which runs migrations and initializes all
db.DropTableIfExists(&User{}, &model.Trip{}, &model.TripKeyPoint{})
db.AutoMigrate(&User{}, &model.Trip{}, &model.TripKeyPoint{})
db.Model(&model.TripKeyPoint{}).AddForeignKey("trip_id", "trips(id)", "CASCADE", "CASCADE")
Users models is just an addon but I leave it in this snippet. Due to many tests, I drop tables at the beginning.
Here is what I receive when i run the code:
?[35m(C:/golang_lab/golang-gorm-tutorial/users.go:36)?[0m
?[33m[2019-09-21 18:40:34]?[0m ?[31;1m pq: column "trip_id" referenced in foreign key constraint does not exist ?[0m
And yeah that's true, when I log into postgres in table trip_key_points there isn't column with a foreign key.
What I need to do, I want to have one TRIP object and then assign other TripKeyPoints.
Any idea what why? Or how can I force GORM to create this column?
I explicitly define foreign key column:
// TripKeyPoint models
type TripKeyPoint struct {
gorm.Model
KPName string
KPDescription string
TripID uint `gorm:"TYPE:integer REFERENCES trips"`
}