Skip to content

Instantly share code, notes, and snippets.

@tab1293
Last active August 13, 2021 15:34
Show Gist options
  • Save tab1293/c966432341f6a49790a4c571e38f6fe0 to your computer and use it in GitHub Desktop.
Save tab1293/c966432341f6a49790a4c571e38f6fe0 to your computer and use it in GitHub Desktop.
GORM Circular Foreign Key Issue
2021/08/13 09:58:54 /Users/tom/go/pkg/mod/gorm.io/driver/postgres@v1.1.0/migrator.go:157 ERROR: relation "logins" does not exist (SQLSTATE 42P01)
[16.528ms] [rows:0] CREATE TABLE "users" ("id" varchar(36),"name" text,"last_login_id" varchar(36),PRIMARY KEY ("id"),CONSTRAINT "fk_users_last_login" FOREIGN KEY ("last_login_id") REFERENCES "logins"("id"))
2021/08/13 09:58:54 Failed to auto migrate, but got error ERROR: relation "logins" does not exist (SQLSTATE 42P01)
type User struct {
ID string `gorm:"column:id;type:varchar(36);primary_key" json:"id"`
Name string
LastLoginID *string `gorm:"column:last_login_id;type:varchar(36);uniqueIndex"`
LastLogin *Login `gorm:"foreignKey:LastLoginID"`
Logins []*Login `gorm:"foreignKey:UserID"`
}
type Login struct {
ID string `gorm:"column:id;type:varchar(36);primary_key" json:"id"`
Location string
UserID string
Time *time.Time
}
DB, err = gorm.Open(postgres.Open(dbDSN), &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
})
DB.Migrator().CreateConstraint(&User{}, "Logins")
DB.Migrator().CreateConstraint(&User{}, "LastLogin")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment