Gorm tags for compound unique key

Viewed 635

How to describe gorm tags for a compound UNIQUE key?

Postgres:

phone_country_code VARCHAR(10), 
phone_number VARCHAR(25),
CONSTRAINT phone_country_code_number UNIQUE (phone_country_code, phone_number)

Go (fields of model struct):

PhoneCountryCode       string    `gorm:"column:phone_country_code; type:VARCHAR(10)"`
PhoneNumber            string    `gorm:"column:phone_number; type:VARCHAR(25)"`
1 Answers

According to the docs on Composite Indexes you can create a unique composite index by using the same index name in two or more fields:

PhoneCountryCode       string    `gorm:"uniqueIndex:idx_code_phone; type:VARCHAR(10)"`
PhoneNumber            string    `gorm:"uniqueIndex:idx_code_phone; type:VARCHAR(25)"`

This will have the same effect as adding a constraint.

(Note: I removed the column tag for legibility, it's not needed as gorm snake cases the field names to get column names by default).

Related