I have following structure and would like to create unique index on (UserId and Contact). Is this possible in gorm?
type Contact struct {
gorm.Model
UserId uint `gorm:"index;not null"`
Contact string `gorm:"type:text;not null"`
}
I would like to create table something like
CREATE TABLE contact (...column definitions ...)
CONSTRAINT constraint1
UNIQUE (user_id, contact)
SQL UNIQUE constraint for 2 columns example Notice that we named the UNIQUE constraints using CONSTRAINT keyword. We can use this name to remove the UNIQUE constraint later if we want. To define a UNIQUE on multiple columns, we put a comma-separated columns list inside parenthesis that follows the UNIQUE keyword.
UNIQUE key does not allow duplicate values. UNIQUE key allows NULL values but does not allow NULL values multiple times. We can create multiple UNIQUE columns on one table however only one PRIMARY KEY for table. Defining primary key on a column has a UNIQUE constraint property by default.
Defining Composite Unique Keys Oracle creates an index on the columns of a unique key, so a composite unique key can contain a maximum of 16 columns.
The doc on models specifies the following for INDEX
and UNIQUE_INDEX
:
INDEX Create index with or without name, same name creates composite indexes
UNIQUE_INDEX Like INDEX, create unique index
This means that two fields with the same UNIQUE_INDEX
name will create a composite unique index.
The full struct definition to use a composite index named compositeindex
using your example becomes:
type Contact struct {
gorm.Model
UserId uint `gorm:"UNIQUE_INDEX:compositeindex;index;not null"`
Contact string `gorm:"UNIQUE_INDEX:compositeindex;type:text;not null"`
}
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