Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

go-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"`
}
like image 968
Johan S Avatar asked Jun 14 '15 15:06

Johan S


People also ask

What is index in Gorm?

GORM allows create database index with tag index , uniqueIndex , those indexes will be created when AutoMigrate or CreateTable with GORM.

What is the difference between index and unique index?

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.

What is DB model in Gorm?

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.

What is Composite index SQL?

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.


3 Answers

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"`
}
like image 86
blue-hope Avatar answered Sep 20 '22 18:09

blue-hope


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"`
}
like image 32
Sebastian Avatar answered Sep 19 '22 18:09

Sebastian


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"`
}
like image 39
Ahmed Hashem Avatar answered Sep 18 '22 18:09

Ahmed Hashem