Home > OS >  How to specify unique together index in gorm?
How to specify unique together index in gorm?

Time:07-08

type ABC struct {
ID uint
 Abc int `gorm:"unidqueIndex;
Bcd string
}

I want Field Abc and Bcd to be unique together

{Abc: 1, Bcd: "hello"} {Abc: 1, Bcd: "hi"} should be valid but

{Abc: 1, Bcd: "hello"} {Abc: 1, Bcd: "hello"} should be invalid

CodePudding user response:

Give both fields the same index name.

type ABC struct {
 ID uint
 Abc int `gorm:"uniqueIndex:abc_bcd_uniq"`
 Bcd string `gorm:"uniqueIndex:abc_bcd_uniq"`
}

See composite indexes in the GORM docs.

  • Related