GORM Playground Link

https://go.dev/play/p/_ejp1Mmag0k

Description

I had an issue when adding uniqueIndex into foreign key column, the query is not what I expected.

type Entity struct {
    ID     uint         `gorm:"column:id" json:"-"`
    UUID   string       `gorm:"column:uuid;type:uuid;uniqueIndex:UQ_admins_uuid;not null;default:uuid_generate_v4()" json:"id"`
    UserID uint         `gorm:"column:user_id;uniqueIndex:UQ_admins_user_id"`
    User   users.Entity `gorm:"foreignKey:UserID;references:ID"`
        ... etc
}

The code are

data := Entity{UserID: 5}
db.Create(&data)

When I create the data, the debug SQL is resulting like this

INSERT INTO "admins" ("user_id") VALUES (8) RETURNING "uuid","id"

And when I try to create again, the user_id in Query is incremented, just like this

INSERT INTO "admins" ("user_id") VALUES (9) RETURNING "uuid","id"

This query is resulting ERROR: insert or update on table "admins" violates foreign key constraint "fk_admins_user" (SQLSTATE 23503)

But if I don't use uniqueIndex. The resulting query is working perfectly as expected.

INSERT INTO "admins" ("user_id") VALUES (5) RETURNING "uuid","id"

How do I resolve this issue? I think this is this a bug.. Or I wrote a wrong code? Or If there any other approach to use unique in foreign key? I also already add the go-playground URL for the example code. Thank u

Comment From: github-actions[bot]

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking

Comment From: akbarhabiby

Nvm i got this, i coded a wrong foreign key reference. Thank u