Last active
August 13, 2021 15:34
-
-
Save tab1293/c966432341f6a49790a4c571e38f6fe0 to your computer and use it in GitHub Desktop.
GORM Circular Foreign Key Issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2021/08/13 09:58:54 /Users/tom/go/pkg/mod/gorm.io/driver/[email protected]/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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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