How do I create unique constraint for multiple columns?

Viewed 3983

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) 
1 Answers

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