Search code examples
postgresqlgogo-gorm

How to specify unique together index in gorm?


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


Solution

  • 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.