How to specify a struct with a multi-column unique index for Gorm?

17.8k views Asked by At

How do I define my structs to specify a multi-column unique index to Gorm in Go?

Such as:

type Something struct {
    gorm.Model
    First  string `sql:"unique_index:unique_index_with_second"`
    Second string `sql:"unique_index:unique_index_with_first"`
}
3

There are 3 answers

0
Sebastian On BEST ANSWER

this is how you do it: You need to use the gorm struct tag and specify that the index is unique

type Something struct {
    gorm.Model
    First  string `gorm:"index:idx_name,unique"`
    Second string `gorm:"index:idx_name,unique"`
}
0
blue-hope On

for latest version of gorm (or for my case) this works:

type Something struct {
    gorm.Model
    First  string `gorm:"uniqueIndex:idx_first_second"`
    Second string `gorm:"uniqueIndex:idx_first_second"`
}
0
Ahmed Hashem On

You can define same unique index for each column.

type Something struct {
    gorm.Model
    First  string `sql:"unique_index:idx_first_second"`
    Second string `sql:"unique_index:idx_first_second"`
}