Johan S
Johan S

Reputation: 3591

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

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

Upvotes: 21

Views: 20690

Answers (3)

blue-hope
blue-hope

Reputation: 3269

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

Upvotes: 13

Sebastian
Sebastian

Reputation: 1853

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

Upvotes: 36

Ahmed Hashem
Ahmed Hashem

Reputation: 4733

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

Upvotes: 14

Related Questions