How do I define my struct
s 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"`
}
GORM allows create database index with tag index , uniqueIndex , those indexes will be created when AutoMigrate or CreateTable with GORM.
Unique indexes are indexes that help maintain data integrity by ensuring that no rows of data in a table have identical key values. When you create a unique index for an existing table with data, values in the columns or expressions that comprise the index key are checked for uniqueness.
db. Model is the ordinary way of doing things. It allows you to tell gorm which model struct this operation relates to. It isn't always needed, as for example a simple Find with the right struct type will infer the model automatically.
An SQL composite index is an index with an index key of more than 1 column. It is good for covering searches and lookups like WHERE clause and joins. You can create composite indexes using CREATE INDEX or ALTER TABLE. An SQL GUI tool can also be used.
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"`
}
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"`
}
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"`
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With