Алекс
Алекс

Reputation: 35

Gorm tags for compound unique key

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)"`

Upvotes: 3

Views: 2291

Answers (1)

Ezequiel Muns
Ezequiel Muns

Reputation: 7762

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).

Upvotes: 5

Related Questions