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

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条回答 默认 最新

  • doure8758 2019-09-22 06:03
    关注

    I explicitly define foreign key column:

    // TripKeyPoint models
    type TripKeyPoint struct {
        gorm.Model
        KPName        string
        KPDescription string
        TripID        uint `gorm:"TYPE:integer REFERENCES trips"`
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?