Gorm: UNIQUE constraint across multiple keys?

Created on 14 Apr 2016  路  5Comments  路  Source: go-gorm/gorm

With gorm, is it currently possible to create a UNIQUE constraint across multiple columns?

(It's the case where I don't think I want to make a composite primary key, but I do want to ensure some set of columns are unique together)

Most helpful comment

This will work:

type Language struct {
    ID   int
    Name string `gorm:"unique_index:idx_name_code"` // Create index with name, and will create combined index if find other fields defined same name
    Code string `gorm:"unique_index:idx_name_code"` // `unique_index` also works
}

All 5 comments

This will work:

type Language struct {
    ID   int
    Name string `gorm:"unique_index:idx_name_code"` // Create index with name, and will create combined index if find other fields defined same name
    Code string `gorm:"unique_index:idx_name_code"` // `unique_index` also works
}

Awesome, thank you!

Shouldn't this be added to the documentation? I couldn't find anything on the subject.

Do db.Model(&User{}).AddUniqueIndex("idx_user_name_age", "name", "age") as shown on Migrations behaves in the same way as the code shown by @klniu?

How can you control the order of the keys in the index? For instance I believe this will be an index of name, code. What if you wanted it to be code, name?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fieryorc picture fieryorc  路  3Comments

sredxny picture sredxny  路  3Comments

Ganitzsh picture Ganitzsh  路  3Comments

hypertornado picture hypertornado  路  3Comments

bramp picture bramp  路  3Comments