-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
AutoMigrate with self-referential belongs to #3624
Comments
Initialize another DB with
Don't think this is a good idea, and you can just set the |
@jinzhu I have already set uniqueIndex on the field. But constraints are created prior to indexes during CREATE TABLE so the query to create the table fails. In this test: gorm/schema/relationship_test.go Lines 58 to 70 in f6ed895
references:ID is set to the primary key, but if one changes it to another ID in the same table, GORM would return an error during AutoMigrate. Here's a link to the playground: go-gorm/playground#184 |
Hi @suciuvlad You could use the type Transaction struct {
gorm.Model
ExternalID uint `gorm:"unique"`
ReferenceID *uint `json:"reference_id" gorm:"unique; type:uuid"`
Reference *Transaction `gorm:"foreignKey:ReferenceID; References:ExternalID"`
} |
@jinzhu that worked! Thank you very much. |
Your Question
I'm trying to perform AutoMigrate on a self-referential table where the model doesn't reference the primary key:
this results in the following SQL query:
CREATE TABLE "transactions" ("id" bigserial,"created_at" timestamptz,"updated_at" timestamptz,"deleted_at" timestamptz,"reference_id" bigint,"external_id" bigint,PRIMARY KEY ("id"),CONSTRAINT "fk_transactions_reference" FOREIGN KEY ("reference_id") REFERENCES "transactions"("external_id"))
that returns the following error:
"ERROR: there is no unique constraint matching given keys for referenced table "transactions" -- This is due to the fact that the constraint expects an unique index on "external_id" that is only created after CREATE TABLE query.
Expected answer
@jinzhu Any thoughts?
The text was updated successfully, but these errors were encountered: