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

feige84 picture feige84  ·  19Comments

aimuz picture aimuz  ·  24Comments

lz1988 picture lz1988  ·  32Comments

samgavinio picture samgavinio  ·  15Comments

kiwih picture kiwih  ·  23Comments