Gorm 2, Golang, Auto migrate table with foreign key

Viewed 732
import  "gorm.io/gorm"

type Object struct {
    gorm.Model
    ObjectId  string      `gorm:"primary_key"`
    ListItems []ListItem `gorm:"foreignKey:ObjectId;references:ObjectId"`
}

type ListItem struct {
    gorm.Model
    ObjectId   string           
    Data string
}

I define two objects, then try to auto migrate following the guide

db.Migrator().CreateConstraint(&Object{}, "ListItems")
db.Migrator().CreateConstraint(&Object{}, "fk_object_list_items")
db.AutoMigrate(&Object{}, &ListItem{})

Fails with

ERROR: there is no unique constraint matching given keys for referenced table "blobber_ch

I can't find any examples for this. I tried different permutations of everything. I suspect the foreign key in the migration does not match the foreign key in the model.

1 Answers

You have two primary_key for Object struct as gorm.Model already have one:

    ID        uint `gorm:"primarykey"`

You have two otpions : not to use gorm.Model or get rid of ObjectId primary_key and clean references:ObjectId from gorm annotation.

type Object struct {
    gorm.Model
    ObjectId  string
    ListItems []ListItem `gorm:"foreignKey:ObjectId;"`
}

type ListItem struct {
    gorm.Model
    ObjectId string
    Data     string
}

db.Migrator().CreateConstraint(&Object{}, "ListItems")
db.Migrator().CreateConstraint(&Object{}, "fk_object_list_items")
db.AutoMigrate(&Object{}, &ListItem{})
Related