drq1257
2019-09-21 16:55
采纳率: 0%
浏览 363

GORM不会创建外键列

I'm trying to setup relation between two models on PostgreSQL database using Go and gorm.

Here is my code, first model:

Trip.go

package model

import "github.com/jinzhu/gorm"

// Trip models
type Trip struct {
    gorm.Model
    TripName        string
    TripDescription string
}

Second model:

TripKeyPoints.go

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?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题