10
votes

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"`
}
4

4 Answers

18
votes

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"`
}
12
votes

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"`
}
3
votes

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"`
}
-11
votes

Are you trying to create a table so that the combination of First and Second is unique?

This should work :

type Something struct {
    ID uint
    gorm.Model
    First  string `gorm:"primary_key"`
    Second string `gorm:"primary_key"`
}